forumfunction.inc.php 233 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Doctrine\Common\Collections\Criteria;
  5. use Chamilo\CourseBundle\Entity\CForumPost;
  6. use Chamilo\CourseBundle\Entity\CForumThread;
  7. /**
  8. * These files are a complete rework of the forum. The database structure is
  9. * based on phpBB but all the code is rewritten. A lot of new functionalities
  10. * are added:
  11. * - forum categories and forums can be sorted up or down, locked or made invisible
  12. * - consistent and integrated forum administration
  13. * - forum options: are students allowed to edit their post?
  14. * moderation of posts (approval)
  15. * reply only forums (students cannot create new threads)
  16. * multiple forums per group
  17. * - sticky messages
  18. * - new view option: nested view
  19. * - quoting a message
  20. *
  21. * @package chamilo.forum
  22. *
  23. * @todo several functions have to be moved to the itemmanager library
  24. * @todo displaying icons => display library
  25. * @todo complete the missing phpdoc the correct order should be
  26. * @todo convert into a class
  27. */
  28. define('FORUM_NEW_POST', 0);
  29. get_notifications_of_user();
  30. $htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui', 'jquery-upload'));
  31. $htmlHeadXtra[] = '<script>
  32. function check_unzip() {
  33. if (document.upload.unzip.checked){
  34. document.upload.if_exists[0].disabled=true;
  35. document.upload.if_exists[1].checked=true;
  36. document.upload.if_exists[2].disabled=true;
  37. } else {
  38. document.upload.if_exists[0].checked=true;
  39. document.upload.if_exists[0].disabled=false;
  40. document.upload.if_exists[2].disabled=false;
  41. }
  42. }
  43. function setFocus() {
  44. $("#title_file").focus();
  45. }
  46. </script>';
  47. // The next javascript script is to manage ajax upload file
  48. $htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui', 'jquery-upload'));
  49. // Recover Thread ID, will be used to generate delete attachment URL to do ajax
  50. $threadId = isset($_REQUEST['thread']) ? intval($_REQUEST['thread']) : 0;
  51. $forumId = isset($_REQUEST['forum']) ? intval($_REQUEST['forum']) : 0;
  52. // The next javascript script is to delete file by ajax
  53. $htmlHeadXtra[] = '<script>
  54. $(function () {
  55. $(document).on("click", ".deleteLink", function(e) {
  56. e.preventDefault();
  57. e.stopPropagation();
  58. var l = $(this);
  59. var id = l.closest("tr").attr("id");
  60. var filename = l.closest("tr").find(".attachFilename").html();
  61. if (confirm("' . get_lang('AreYouSureToDeleteJS') . '", filename)) {
  62. $.ajax({
  63. type: "POST",
  64. url: "'.api_get_path(WEB_AJAX_PATH) . 'forum.ajax.php?'.api_get_cidreq().'&a=delete_file&attachId=" + id +"&thread='.$threadId .'&forum='.$forumId .'",
  65. dataType: "json",
  66. success: function(data) {
  67. if (data.error == false) {
  68. l.closest("tr").remove();
  69. if ($(".files td").length < 1) {
  70. $(".files").closest(".control-group").hide();
  71. }
  72. }
  73. }
  74. })
  75. }
  76. });
  77. });
  78. </script>';
  79. /**
  80. * This function handles all the forum and forum categories actions. This is a wrapper for the
  81. * forum and forum categories. All this code code could go into the section where this function is
  82. * called but this make the code there cleaner.
  83. * @param int $lp_id Learning path Id
  84. *
  85. * @return void
  86. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  87. * @author Juan Carlos Raña Trabado (return to lp_id)
  88. * @version may 2011, Chamilo 1.8.8
  89. */
  90. function handle_forum_and_forumcategories($lp_id = null)
  91. {
  92. $action_forum_cat = isset($_GET['action']) ? $_GET['action'] : '';
  93. $get_content = isset($_GET['content']) ? $_GET['content'] : '';
  94. $post_submit_cat = isset($_POST['SubmitForumCategory']) ? true : false;
  95. $post_submit_forum = isset($_POST['SubmitForum']) ? true : false;
  96. $get_id = isset($_GET['id']) ? intval($_GET['id']) : '';
  97. $forum_categories_list = get_forum_categories();
  98. //Verify if forum category exists
  99. if (empty($forum_categories_list)) {
  100. $get_content = 'forumcategory';
  101. }
  102. // Adding a forum category
  103. if (($action_forum_cat == 'add' && $get_content == 'forumcategory') || $post_submit_cat) {
  104. show_add_forumcategory_form(array(), $lp_id); //$lp_id when is called from learning path
  105. }
  106. // Adding a forum
  107. if ((($action_forum_cat == 'add' || $action_forum_cat == 'edit') && $get_content == 'forum') || $post_submit_forum) {
  108. if ($action_forum_cat == 'edit' && $get_id || $post_submit_forum) {
  109. $inputvalues = get_forums($get_id);
  110. } else {
  111. $inputvalues = array();
  112. }
  113. show_add_forum_form($inputvalues, $lp_id);
  114. }
  115. // Edit a forum category
  116. if (($action_forum_cat == 'edit' && $get_content == 'forumcategory') || (isset($_POST['SubmitEditForumCategory'])) ? true : false) {
  117. $forum_category = get_forum_categories($get_id);
  118. show_edit_forumcategory_form($forum_category);
  119. }
  120. // Delete a forum category
  121. if ($action_forum_cat == 'delete') {
  122. $id_forum = intval($get_id);
  123. $list_threads = get_threads($id_forum);
  124. for ($i = 0; $i < count($list_threads); $i++) {
  125. deleteForumCategoryThread('thread', $list_threads[$i]['thread_id']);
  126. $link_info = GradebookUtils::isResourceInCourseGradebook(
  127. api_get_course_id(),
  128. 5,
  129. $list_threads[$i]['thread_id'],
  130. api_get_session_id()
  131. );
  132. if ($link_info !== false) {
  133. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  134. }
  135. }
  136. $return_message = deleteForumCategoryThread($get_content, $get_id);
  137. Display::display_confirmation_message($return_message, false);
  138. }
  139. // Change visibility of a forum or a forum category.
  140. if ($action_forum_cat == 'invisible' || $action_forum_cat == 'visible') {
  141. $return_message = change_visibility($get_content, $get_id, $action_forum_cat);
  142. Display::display_confirmation_message($return_message, false);
  143. }
  144. // Change lock status of a forum or a forum category.
  145. if ($action_forum_cat == 'lock' || $action_forum_cat == 'unlock') {
  146. $return_message = change_lock_status($get_content, $get_id, $action_forum_cat);
  147. Display::display_confirmation_message($return_message, false);
  148. }
  149. // Move a forum or a forum category.
  150. if ($action_forum_cat == 'move' && isset($_GET['direction'])) {
  151. $return_message = move_up_down($get_content, $_GET['direction'], $get_id);
  152. Display::display_confirmation_message($return_message, false);
  153. }
  154. }
  155. /**
  156. * This function displays the form that is used to add a forum category.
  157. *
  158. * @param array $inputvalues (deprecated, set to null when calling)
  159. * @param int $lp_id Learning path ID
  160. *
  161. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  162. * @author Juan Carlos Raña Trabado (return to lp_id)
  163. * @version may 2011, Chamilo 1.8.8
  164. */
  165. function show_add_forumcategory_form($inputvalues = array(), $lp_id)
  166. {
  167. $form = new FormValidator('forumcategory', 'post', 'index.php?' . api_get_cidreq());
  168. // hidden field if from learning path
  169. $form->addElement('hidden', 'lp_id', $lp_id);
  170. // Setting the form elements.
  171. $form->addElement('header', get_lang('AddForumCategory'));
  172. $form->addElement('text', 'forum_category_title', get_lang('Title'), array('autofocus'));
  173. $form->addElement(
  174. 'html_editor',
  175. 'forum_category_comment',
  176. get_lang('Description'),
  177. null,
  178. array('ToolbarSet' => 'Forum', 'Width' => '98%', 'Height' => '200')
  179. );
  180. $form->addButtonCreate(get_lang('CreateCategory'), 'SubmitForumCategory');
  181. // Setting the rules.
  182. $form->addRule('forum_category_title', get_lang('ThisFieldIsRequired'), 'required');
  183. // The validation or display
  184. if ($form->validate()) {
  185. $check = Security::check_token('post');
  186. if ($check) {
  187. $values = $form->exportValues();
  188. store_forumcategory($values);
  189. }
  190. Security::clear_token();
  191. } else {
  192. $token = Security::get_token();
  193. $form->addElement('hidden', 'sec_token');
  194. $form->setConstants(array('sec_token' => $token));
  195. $form->display();
  196. }
  197. }
  198. /**
  199. * This function displays the form that is used to add a forum category.
  200. *
  201. * @param array $inputvalues
  202. * @param int $lp_id
  203. * @return void HTML
  204. *
  205. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  206. * @author Juan Carlos Raña Trabado (return to lp_id)
  207. *
  208. * @version may 2011, Chamilo 1.8.8
  209. */
  210. function show_add_forum_form($inputvalues = array(), $lp_id)
  211. {
  212. $_course = api_get_course_info();
  213. $form = new FormValidator('forumcategory', 'post', 'index.php?' . api_get_cidreq());
  214. // The header for the form
  215. if (!empty($inputvalues)) {
  216. $form_title = get_lang('EditForum');
  217. } else {
  218. $form_title = get_lang('AddForum');
  219. }
  220. $session_header = api_get_session_name();
  221. $form->addElement('header', $form_title.$session_header);
  222. // We have a hidden field if we are editing.
  223. if (!empty($inputvalues) && is_array($inputvalues)) {
  224. $my_forum_id = isset($inputvalues['forum_id']) ? $inputvalues['forum_id'] : null;
  225. $form->addElement('hidden', 'forum_id', $my_forum_id);
  226. }
  227. $lp_id = intval($lp_id);
  228. // hidden field if from learning path
  229. $form->addElement('hidden', 'lp_id', $lp_id);
  230. // The title of the forum
  231. $form->addElement('text', 'forum_title', get_lang('Title'), array('autofocus'));
  232. // The comment of the forum.
  233. $form->addElement(
  234. 'html_editor',
  235. 'forum_comment',
  236. get_lang('Description'),
  237. null,
  238. array('ToolbarSet' => 'Forum', 'Width' => '98%', 'Height' => '200')
  239. );
  240. // Dropdown list: Forum categories
  241. $forum_categories = get_forum_categories();
  242. foreach ($forum_categories as $key => $value) {
  243. $forum_categories_titles[$value['cat_id']] = $value['cat_title'];
  244. }
  245. $form->addElement('select', 'forum_category', get_lang('InForumCategory'), $forum_categories_titles);
  246. $form->applyFilter('forum_category', 'html_filter');
  247. if ($_course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD) {
  248. // This is for horizontal
  249. $group = array();
  250. $group[] = $form->createElement('radio', 'allow_anonymous', null, get_lang('Yes'), 1);
  251. $group[] = $form->createElement('radio', 'allow_anonymous', null, get_lang('No'), 0);
  252. $form->addGroup($group, 'allow_anonymous_group', get_lang('AllowAnonymousPosts'));
  253. }
  254. $form->addButtonAdvancedSettings('advanced_params');
  255. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  256. $form->addDateTimePicker(
  257. 'start_time',
  258. array(get_lang('ForumStartDate'), get_lang('ForumStartDateComment')),
  259. array('id' => 'start_time')
  260. );
  261. $form->addDateTimePicker(
  262. 'end_time',
  263. array(get_lang('ForumEndDate'), get_lang('ForumEndDateComment')),
  264. array('id' => 'end_time')
  265. );
  266. $form->addRule(
  267. array('start_time', 'end_time'),
  268. get_lang('StartDateMustBeBeforeTheEndDate'),
  269. 'compare_datetime_text',
  270. '< allow_empty'
  271. );
  272. $group = array();
  273. $group[] = $form->createElement('radio', 'moderated', null, get_lang('Yes'), 1);
  274. $group[] = $form->createElement('radio', 'moderated', null, get_lang('No'), 0);
  275. $form->addGroup($group, 'moderated', get_lang('ModeratedForum'));
  276. $group = array();
  277. $group[] = $form->createElement('radio', 'students_can_edit', null, get_lang('Yes'), 1);
  278. $group[] = $form->createElement('radio', 'students_can_edit', null, get_lang('No'), 0);
  279. $form->addGroup($group, 'students_can_edit_group', get_lang('StudentsCanEdit'));
  280. $group = array();
  281. $group[] = $form->createElement('radio', 'approval_direct', null, get_lang('Approval'), 1);
  282. $group[] = $form->createElement('radio', 'approval_direct', null, get_lang('Direct'), 0);
  283. $group = array();
  284. $group[] = $form->createElement('radio', 'allow_attachments', null, get_lang('Yes'), 1);
  285. $group[] = $form->createElement('radio', 'allow_attachments', null, get_lang('No'), 0);
  286. $group = array();
  287. $group[] = $form->createElement('radio', 'allow_new_threads', null, get_lang('Yes'), 1);
  288. $group[] = $form->createElement('radio', 'allow_new_threads', null, get_lang('No'), 0);
  289. $form->addGroup($group, 'allow_new_threads_group', get_lang('AllowNewThreads'));
  290. $group = array();
  291. $group[] = $form->createElement('radio', 'default_view_type', null, get_lang('Flat'), 'flat');
  292. $group[] = $form->createElement('radio', 'default_view_type', null, get_lang('Threaded'), 'threaded');
  293. $group[] = $form->createElement('radio', 'default_view_type', null, get_lang('Nested'), 'nested');
  294. $form->addGroup($group, 'default_view_type_group', get_lang('DefaultViewType'));
  295. // Drop down list: Groups
  296. $groups = GroupManager::get_group_list();
  297. $groups_titles[0] = get_lang('NotAGroupForum');
  298. foreach ($groups as $key => $value) {
  299. $groups_titles[$value['id']] = $value['name'];
  300. }
  301. $form->addElement('select', 'group_forum', get_lang('ForGroup'), $groups_titles);
  302. // Public or private group forum
  303. $group = array();
  304. $group[] = $form->createElement('radio', 'public_private_group_forum', null, get_lang('Public'), 'public');
  305. $group[] = $form->createElement('radio', 'public_private_group_forum', null, get_lang('Private'), 'private');
  306. $form->addGroup($group, 'public_private_group_forum_group', get_lang('PublicPrivateGroupForum'));
  307. // Forum image
  308. $form->addProgress();
  309. if (!empty($inputvalues['forum_image'])) {
  310. $baseImagePath = api_get_course_path() . '/upload/forum/images/' . $inputvalues['forum_image'];
  311. $image_path = api_get_path(WEB_COURSE_PATH) . $baseImagePath;
  312. $sysImagePath = api_get_path(SYS_COURSE_PATH) . $baseImagePath;
  313. if (file_exists($sysImagePath)) {
  314. $show_preview_image = Display::img($image_path, null, ['class' => 'img-responsive']);
  315. $form->addElement('label', get_lang('PreviewImage'), $show_preview_image);
  316. $form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
  317. }
  318. }
  319. $forum_image = isset($inputvalues['forum_image']) ? $inputvalues['forum_image'] : '';
  320. $form->addElement('file', 'picture', ($forum_image != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
  321. $form->addRule('picture', get_lang('OnlyImagesAllowed'), 'filetype', array('jpg', 'jpeg', 'png', 'gif'));
  322. $form->addElement('html', '</div>');
  323. // The OK button
  324. if (isset($_GET['id']) && $_GET['action'] == 'edit') {
  325. $form->addButtonUpdate(get_lang('ModifyForum'), 'SubmitForum');
  326. } else {
  327. $form->addButtonCreate(get_lang('CreateForum'), 'SubmitForum');
  328. }
  329. // setting the rules
  330. $form->addRule('forum_title', get_lang('ThisFieldIsRequired'), 'required');
  331. $form->addRule('forum_category', get_lang('ThisFieldIsRequired'), 'required');
  332. $defaultSettingAllowNewThreads = api_get_default_tool_setting('forum', 'allow_new_threads', 0);
  333. // Settings the defaults
  334. if (empty($inputvalues) || !is_array($inputvalues)) {
  335. $defaults['moderated']['moderated'] = 0;
  336. $defaults['allow_anonymous_group']['allow_anonymous'] = 0;
  337. $defaults['students_can_edit_group']['students_can_edit'] = 0;
  338. $defaults['approval_direct_group']['approval_direct'] = 0;
  339. $defaults['allow_attachments_group']['allow_attachments'] = 1;
  340. $defaults['allow_new_threads_group']['allow_new_threads'] = $defaultSettingAllowNewThreads;
  341. $defaults['default_view_type_group']['default_view_type'] = api_get_setting('default_forum_view');
  342. $defaults['public_private_group_forum_group']['public_private_group_forum'] = 'public';
  343. if (isset($_GET['forumcategory'])) {
  344. $defaults['forum_category'] = Security::remove_XSS($_GET['forumcategory']);
  345. }
  346. } else {
  347. // the default values when editing = the data in the table
  348. $defaults['forum_id'] = isset($inputvalues['forum_id']) ? $inputvalues['forum_id'] : null;
  349. $defaults['forum_title'] = prepare4display(isset($inputvalues['forum_title']) ? $inputvalues['forum_title'] : null);
  350. $defaults['forum_comment'] = prepare4display(isset($inputvalues['forum_comment']) ? $inputvalues['forum_comment'] : null);
  351. $defaults['start_time'] = isset($inputvalues['start_time']) ? api_get_local_time($inputvalues['start_time']) : null;
  352. $defaults['end_time'] = isset($inputvalues['end_time']) ? api_get_local_time($inputvalues['end_time']) : null;
  353. $defaults['moderated']['moderated'] = isset($inputvalues['moderated']) ? $inputvalues['moderated'] : 0;
  354. $defaults['forum_category'] = isset($inputvalues['forum_category']) ? $inputvalues['forum_category'] : null;
  355. $defaults['allow_anonymous_group']['allow_anonymous'] = isset($inputvalues['allow_anonymous']) ? $inputvalues['allow_anonymous'] : null;
  356. $defaults['students_can_edit_group']['students_can_edit'] = isset($inputvalues['allow_edit']) ? $inputvalues['allow_edit'] : null;
  357. $defaults['approval_direct_group']['approval_direct'] = isset($inputvalues['approval_direct_post']) ? $inputvalues['approval_direct_post'] : null;
  358. $defaults['allow_attachments_group']['allow_attachments'] = isset($inputvalues['allow_attachments']) ? $inputvalues['allow_attachments'] : null;
  359. $defaults['allow_new_threads_group']['allow_new_threads'] = isset($inputvalues['allow_new_threads']) ? $inputvalues['allow_new_threads'] : $defaultSettingAllowNewThreads;
  360. $defaults['default_view_type_group']['default_view_type'] = isset($inputvalues['default_view']) ? $inputvalues['default_view'] : null;
  361. $defaults['public_private_group_forum_group']['public_private_group_forum'] = isset($inputvalues['forum_group_public_private']) ? $inputvalues['forum_group_public_private'] : null;
  362. $defaults['group_forum'] = isset($inputvalues['forum_of_group']) ? $inputvalues['forum_of_group'] : null;
  363. }
  364. $form->setDefaults($defaults);
  365. // Validation or display
  366. if ($form->validate()) {
  367. $check = Security::check_token('post');
  368. if ($check) {
  369. $values = $form->getSubmitValues();
  370. $return_message = store_forum($values);
  371. Display :: display_confirmation_message($return_message);
  372. }
  373. Security::clear_token();
  374. } else {
  375. $token = Security::get_token();
  376. $form->addElement('hidden', 'sec_token');
  377. $form->setConstants(array('sec_token' => $token));
  378. $form->display();
  379. }
  380. }
  381. /**
  382. * This function deletes the forum image if exists
  383. *
  384. * @param int forum id
  385. * @return boolean true if success
  386. * @author Julio Montoya <gugli100@gmail.com>
  387. * @version february 2006, dokeos 1.8
  388. */
  389. function delete_forum_image($forum_id)
  390. {
  391. $table_forums = Database::get_course_table(TABLE_FORUM);
  392. $course_id = api_get_course_int_id();
  393. $forum_id = intval($forum_id);
  394. $sql = "SELECT forum_image FROM $table_forums
  395. WHERE forum_id = $forum_id AND c_id = $course_id";
  396. $result = Database::query($sql);
  397. $row = Database::fetch_array($result);
  398. if ($row['forum_image'] != '') {
  399. $file = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/forum/images/'.$row['forum_image'];
  400. if (file_exists($file)) {
  401. unlink($file);
  402. }
  403. return true;
  404. } else {
  405. return false;
  406. }
  407. }
  408. /**
  409. * This function displays the form that is used to edit a forum category.
  410. * This is more or less a copy from the show_add_forumcategory_form function with the only difference that is uses
  411. * some default values. I tried to have both in one function but this gave problems with the handle_forum_and_forumcategories function
  412. * (storing was done twice)
  413. *
  414. * @param array
  415. * @return void HTML
  416. *
  417. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  418. * @version february 2006, dokeos 1.8
  419. */
  420. function show_edit_forumcategory_form($inputvalues = array())
  421. {
  422. $categoryId = $inputvalues['cat_id'];
  423. $form = new FormValidator('forumcategory', 'post', 'index.php?'.api_get_cidreq().'&id='.$categoryId);
  424. // Setting the form elements.
  425. $form->addElement('header', '', get_lang('EditForumCategory'));
  426. $form->addElement('hidden', 'forum_category_id');
  427. $form->addElement('text', 'forum_category_title', get_lang('Title'));
  428. $form->addElement(
  429. 'html_editor',
  430. 'forum_category_comment',
  431. get_lang('Comment'),
  432. null,
  433. array('ToolbarSet' => 'Forum', 'Width' => '98%', 'Height' => '200')
  434. );
  435. $form->addButtonUpdate(get_lang('ModifyCategory'), 'SubmitEditForumCategory');
  436. // Setting the default values.
  437. $defaultvalues['forum_category_id'] = $inputvalues['cat_id'];
  438. $defaultvalues['forum_category_title'] = $inputvalues['cat_title'];
  439. $defaultvalues['forum_category_comment'] = $inputvalues['cat_comment'];
  440. $form->setDefaults($defaultvalues);
  441. // Setting the rules.
  442. $form->addRule('forum_category_title', get_lang('ThisFieldIsRequired'), 'required');
  443. // Validation or display
  444. if ($form->validate()) {
  445. $check = Security::check_token('post');
  446. if ($check) {
  447. $values = $form->exportValues();
  448. store_forumcategory($values);
  449. }
  450. Security::clear_token();
  451. } else {
  452. $token = Security::get_token();
  453. $form->addElement('hidden', 'sec_token');
  454. $form->setConstants(array('sec_token' => $token));
  455. $form->display();
  456. }
  457. }
  458. /**
  459. * This function stores the forum category in the database.
  460. * The new category is added to the end.
  461. *
  462. * @param array $values
  463. * @param array $courseInfo
  464. * @param bool $showMessage
  465. * @return void HMTL language variable
  466. *
  467. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  468. * @version february 2006, dokeos 1.8
  469. */
  470. function store_forumcategory($values, $courseInfo = array(), $showMessage = true)
  471. {
  472. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  473. $course_id = $courseInfo['real_id'];
  474. $table_categories = Database::get_course_table(TABLE_FORUM_CATEGORY);
  475. // Find the max cat_order. The new forum category is added at the end => max cat_order + &
  476. $sql = "SELECT MAX(cat_order) as sort_max
  477. FROM $table_categories
  478. WHERE c_id = $course_id";
  479. $result = Database::query($sql);
  480. $row = Database::fetch_array($result);
  481. $new_max = $row['sort_max'] + 1;
  482. $session_id = api_get_session_id();
  483. $clean_cat_title = $values['forum_category_title'];
  484. $last_id = null;
  485. if (isset($values['forum_category_id'])) {
  486. // Storing after edition.
  487. $params = [
  488. 'cat_title' => $clean_cat_title,
  489. 'cat_comment' => isset($values['forum_category_comment']) ? $values['forum_category_comment'] : '',
  490. ];
  491. Database::update(
  492. $table_categories,
  493. $params,
  494. [
  495. 'c_id = ? AND cat_id = ?' => [
  496. $course_id,
  497. $values['forum_category_id'],
  498. ],
  499. ]
  500. );
  501. api_item_property_update(
  502. $courseInfo,
  503. TOOL_FORUM_CATEGORY,
  504. $values['forum_category_id'],
  505. 'ForumCategoryUpdated',
  506. api_get_user_id()
  507. );
  508. $return_message = get_lang('ForumCategoryEdited');
  509. } else {
  510. $params = [
  511. 'c_id' => $course_id,
  512. 'cat_title' => $clean_cat_title,
  513. 'cat_comment' => isset($values['forum_category_comment']) ? $values['forum_category_comment'] : '',
  514. 'cat_order' => $new_max,
  515. 'session_id' => $session_id,
  516. 'locked' => 0,
  517. 'cat_id' => 0
  518. ];
  519. $last_id = Database::insert($table_categories, $params);
  520. if ($last_id > 0) {
  521. $sql = "UPDATE $table_categories SET cat_id = $last_id WHERE iid = $last_id";
  522. Database::query($sql);
  523. api_item_property_update(
  524. $courseInfo,
  525. TOOL_FORUM_CATEGORY,
  526. $last_id,
  527. 'ForumCategoryAdded',
  528. api_get_user_id()
  529. );
  530. api_set_default_visibility(
  531. $last_id,
  532. TOOL_FORUM_CATEGORY,
  533. 0,
  534. $courseInfo
  535. );
  536. }
  537. $return_message = get_lang('ForumCategoryAdded');
  538. }
  539. if ($showMessage) {
  540. Display::display_confirmation_message($return_message, 'success');
  541. }
  542. return $last_id;
  543. }
  544. /**
  545. * This function stores the forum in the database. The new forum is added to the end.
  546. *
  547. * @param array $values
  548. * @param array $courseInfo
  549. * @param bool $returnId
  550. * @return string language variable
  551. *
  552. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  553. * @version february 2006, dokeos 1.8
  554. */
  555. function store_forum($values, $courseInfo = array(), $returnId = false)
  556. {
  557. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  558. $course_id = $courseInfo['real_id'];
  559. $session_id = api_get_session_id();
  560. if (isset($values['group_id']) && !empty($values['group_id'])) {
  561. $group_id = $values['group_id'];
  562. } else {
  563. $group_id = api_get_group_id();
  564. }
  565. $table_forums = Database::get_course_table(TABLE_FORUM);
  566. // Find the max forum_order for the given category. The new forum is added at the end => max cat_order + &
  567. if (is_null($values['forum_category'])) {
  568. $new_max = null;
  569. } else {
  570. $sql = "SELECT MAX(forum_order) as sort_max
  571. FROM $table_forums
  572. WHERE
  573. c_id = $course_id AND
  574. forum_category='".Database::escape_string($values['forum_category'])."'";
  575. $result = Database::query($sql);
  576. $row = Database::fetch_array($result);
  577. $new_max = $row['sort_max'] + 1;
  578. }
  579. // Forum images
  580. $image_moved = false;
  581. $has_attachment = false;
  582. if (!empty($_FILES['picture']['name'])) {
  583. $upload_ok = process_uploaded_file($_FILES['picture']);
  584. $has_attachment = true;
  585. } else {
  586. $image_moved = true;
  587. }
  588. // Remove existing picture if it was requested.
  589. if (!empty($_POST['remove_picture'])) {
  590. delete_forum_image($values['forum_id']);
  591. }
  592. $new_file_name = '';
  593. if (isset($upload_ok)) {
  594. if ($has_attachment) {
  595. $course_dir = $courseInfo['path'].'/upload/forum/images';
  596. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  597. $updir = $sys_course_path.$course_dir;
  598. // Try to add an extension to the file if it hasn't one.
  599. $new_file_name = add_ext_on_mime(
  600. Database::escape_string($_FILES['picture']['name']),
  601. $_FILES['picture']['type']
  602. );
  603. if (!filter_extension($new_file_name)) {
  604. //Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
  605. $image_moved = false;
  606. } else {
  607. $file_extension = explode('.', $_FILES['picture']['name']);
  608. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  609. $new_file_name = uniqid('').'.'.$file_extension;
  610. $new_path = $updir.'/'.$new_file_name;
  611. $result = @move_uploaded_file($_FILES['picture']['tmp_name'], $new_path);
  612. // Storing the attachments if any
  613. if ($result) {
  614. $image_moved = true;
  615. }
  616. }
  617. }
  618. }
  619. if (isset($values['forum_id'])) {
  620. // Storing after edition.
  621. $params = [
  622. 'forum_title'=> $values['forum_title'],
  623. 'forum_comment'=> isset($values['forum_comment']) ? $values['forum_comment'] : null,
  624. 'forum_category'=> isset($values['forum_category']) ? $values['forum_category'] : null,
  625. 'allow_anonymous'=> isset($values['allow_anonymous_group']['allow_anonymous']) ? $values['allow_anonymous_group']['allow_anonymous'] : null,
  626. 'allow_edit'=> isset($values['students_can_edit_group']['students_can_edit']) ? $values['students_can_edit_group']['students_can_edit'] : null,
  627. 'approval_direct_post'=> isset($values['approval_direct_group']['approval_direct']) ? $values['approval_direct_group']['approval_direct'] : null,
  628. 'allow_attachments'=> isset($values['allow_attachments_group']['allow_attachments']) ? $values['allow_attachments_group']['allow_attachments'] : null,
  629. 'allow_new_threads'=> isset($values['allow_new_threads_group']['allow_new_threads']) ? $values['allow_new_threads_group']['allow_new_threads'] : null,
  630. 'default_view'=> isset($values['default_view_type_group']['default_view_type']) ? $values['default_view_type_group']['default_view_type'] : null,
  631. 'forum_of_group'=> isset($values['group_forum']) ? $values['group_forum'] : null,
  632. 'forum_group_public_private'=> isset($values['public_private_group_forum_group']['public_private_group_forum']) ? $values['public_private_group_forum_group']['public_private_group_forum'] : null,
  633. 'moderated'=> $values['moderated']['moderated'],
  634. 'start_time' => !empty($values['start_time']) ? api_get_utc_datetime($values['start_time']) : null,
  635. 'end_time' => !empty($values['end_time']) ? api_get_utc_datetime($values['end_time']) : null,
  636. 'session_id'=> $session_id,
  637. 'lp_id' => isset($values['lp_id']) ? intval($values['lp_id']) : 0
  638. ];
  639. if (isset($upload_ok)) {
  640. if ($has_attachment) {
  641. $params['forum_image'] = $new_file_name;
  642. }
  643. }
  644. if (isset($values['remove_picture']) && $values['remove_picture'] == 1) {
  645. $params['forum_image'] = '';
  646. delete_forum_image($values['forum_id']);
  647. }
  648. Database::update(
  649. $table_forums,
  650. $params,
  651. ['c_id = ? AND forum_id = ?' => [$course_id, $values['forum_id']]]
  652. );
  653. api_item_property_update(
  654. $courseInfo,
  655. TOOL_FORUM,
  656. Database::escape_string($values['forum_id']),
  657. 'ForumUpdated',
  658. api_get_user_id(),
  659. $group_id
  660. );
  661. $return_message = get_lang('ForumEdited');
  662. } else {
  663. if ($image_moved) {
  664. $new_file_name = isset($new_file_name) ? $new_file_name : '';
  665. }
  666. $params = [
  667. 'c_id' => $course_id,
  668. 'forum_title'=> $values['forum_title'],
  669. 'forum_image'=> $new_file_name,
  670. 'forum_comment'=> isset($values['forum_comment']) ? $values['forum_comment'] : null,
  671. 'forum_category'=> isset($values['forum_category']) ? $values['forum_category'] : null,
  672. 'allow_anonymous'=> isset($values['allow_anonymous_group']['allow_anonymous']) ? $values['allow_anonymous_group']['allow_anonymous'] : null,
  673. 'allow_edit'=> isset($values['students_can_edit_group']['students_can_edit']) ? $values['students_can_edit_group']['students_can_edit'] : null,
  674. 'approval_direct_post'=> isset($values['approval_direct_group']['approval_direct']) ? $values['approval_direct_group']['approval_direct'] : null,
  675. 'allow_attachments'=> isset($values['allow_attachments_group']['allow_attachments']) ? $values['allow_attachments_group']['allow_attachments'] : null,
  676. 'allow_new_threads'=> isset($values['allow_new_threads_group']['allow_new_threads']) ? $values['allow_new_threads_group']['allow_new_threads'] : null,
  677. 'default_view'=> isset($values['default_view_type_group']['default_view_type']) ? $values['default_view_type_group']['default_view_type'] : null,
  678. 'forum_of_group'=> isset($values['group_forum']) ? $values['group_forum'] : null,
  679. 'forum_group_public_private'=> isset($values['public_private_group_forum_group']['public_private_group_forum']) ? $values['public_private_group_forum_group']['public_private_group_forum'] : null,
  680. 'moderated'=> isset($values['moderated']['moderated']) ? (int) $values['moderated']['moderated'] : 0,
  681. 'start_time' => !empty($values['start_time']) ? api_get_utc_datetime($values['start_time']) : null,
  682. 'end_time' => !empty($values['end_time']) ? api_get_utc_datetime($values['end_time']) : null,
  683. 'forum_order'=> isset($new_max) ? $new_max : null,
  684. 'session_id'=> $session_id,
  685. 'lp_id' => isset($values['lp_id']) ? intval($values['lp_id']) : 0,
  686. 'locked' => 0,
  687. 'forum_id' => 0
  688. ];
  689. $last_id = Database::insert($table_forums, $params);
  690. if ($last_id > 0) {
  691. $sql = "UPDATE $table_forums SET forum_id = iid WHERE iid = $last_id";
  692. Database::query($sql);
  693. api_item_property_update(
  694. $courseInfo,
  695. TOOL_FORUM,
  696. $last_id,
  697. 'ForumAdded',
  698. api_get_user_id(),
  699. $group_id
  700. );
  701. api_set_default_visibility(
  702. $last_id,
  703. TOOL_FORUM,
  704. $group_id,
  705. $courseInfo
  706. );
  707. }
  708. $return_message = get_lang('ForumAdded');
  709. if ($returnId) {
  710. return $last_id;
  711. }
  712. }
  713. return $return_message;
  714. }
  715. /**
  716. * This function deletes a forum or a forum category
  717. * This function currently does not delete the forums inside the category,
  718. * nor the threads and replies inside these forums.
  719. * For the moment this is the easiest method and it has the advantage that it
  720. * allows to recover fora that were acidently deleted
  721. * when the forum category got deleted.
  722. *
  723. * @param $content = what we are deleting (a forum or a forum category)
  724. * @param $id The id of the forum category that has to be deleted.
  725. *
  726. * @todo write the code for the cascading deletion of the forums inside a
  727. * forum category and also the threads and replies inside these forums
  728. * @todo config setting for recovery or not
  729. * (see also the documents tool: real delete or not).
  730. * @return string
  731. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  732. * @version february 2006, dokeos 1.8
  733. */
  734. function deleteForumCategoryThread($content, $id)
  735. {
  736. $_course = api_get_course_info();
  737. $table_forums = Database::get_course_table(TABLE_FORUM);
  738. $table_forums_post = Database::get_course_table(TABLE_FORUM_POST);
  739. $table_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
  740. $course_id = api_get_course_int_id();
  741. $groupId = api_get_group_id();
  742. $userId = api_get_user_id();
  743. $id = intval($id);
  744. // Delete all attachment file about this tread id.
  745. $sql = "SELECT post_id FROM $table_forums_post
  746. WHERE c_id = $course_id AND thread_id = '".$id."' ";
  747. $res = Database::query($sql);
  748. while ($poster_id = Database::fetch_row($res)) {
  749. delete_attachment($poster_id[0]);
  750. }
  751. $tool_constant = null;
  752. $return_message = '';
  753. if ($content == 'forumcategory') {
  754. $tool_constant = TOOL_FORUM_CATEGORY;
  755. $return_message = get_lang('ForumCategoryDeleted');
  756. if (!empty($forum_list)) {
  757. $sql = "SELECT forum_id FROM $table_forums
  758. WHERE c_id = $course_id AND forum_category='".$id."'";
  759. $result = Database::query($sql);
  760. $row = Database::fetch_array($result);
  761. foreach ($row as $arr_forum) {
  762. $forum_id = $arr_forum['forum_id'];
  763. api_item_property_update(
  764. $_course,
  765. 'forum',
  766. $forum_id,
  767. 'delete',
  768. api_get_user_id()
  769. );
  770. }
  771. }
  772. }
  773. if ($content == 'forum') {
  774. $tool_constant = TOOL_FORUM;
  775. $return_message = get_lang('ForumDeleted');
  776. if (!empty($number_threads)) {
  777. $sql = "SELECT thread_id FROM $table_forum_thread
  778. WHERE c_id = $course_id AND forum_id = $id ";
  779. $result = Database::query($sql);
  780. $row = Database::fetch_array($result);
  781. foreach ($row as $arr_forum) {
  782. $forum_id = $arr_forum['thread_id'];
  783. api_item_property_update(
  784. $_course,
  785. 'forum_thread',
  786. $forum_id,
  787. 'delete',
  788. api_get_user_id()
  789. );
  790. }
  791. }
  792. }
  793. if ($content == 'thread') {
  794. $tool_constant = TOOL_FORUM_THREAD;
  795. $return_message = get_lang('ThreadDeleted');
  796. }
  797. api_item_property_update(
  798. $_course,
  799. $tool_constant,
  800. $id,
  801. 'delete',
  802. $userId,
  803. $groupId
  804. );
  805. // Check if this returns a true and if so => return $return_message, if not => return false;
  806. return $return_message;
  807. }
  808. /**
  809. * This function deletes a forum post. This separate function is needed because forum posts do not appear in the item_property table (yet)
  810. * and because deleting a post also has consequence on the posts that have this post as parent_id (they are also deleted).
  811. * an alternative would be to store the posts also in item_property and mark this post as deleted (visibility = 2).
  812. * We also have to decrease the number of replies in the thread table
  813. *
  814. * @param $post_id the id of the post that will be deleted
  815. * @todo write recursive function that deletes all the posts that have this message as parent
  816. * @return string language variable
  817. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  818. * @author Hubert Borderiou Function cleanead and fixed
  819. * @version february 2006
  820. */
  821. function delete_post($post_id)
  822. {
  823. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  824. $post_id = intval($post_id);
  825. $course_id = api_get_course_int_id();
  826. $em = Database::getManager();
  827. $post = $em
  828. ->getRepository('ChamiloCourseBundle:CForumPost')
  829. ->findOneBy(['cId' => $course_id, 'postId' => $post_id]);
  830. if ($post) {
  831. $em
  832. ->createQuery('
  833. UPDATE ChamiloCourseBundle:CForumPost p
  834. SET p.postParentId = :parent_of_deleted_post
  835. WHERE
  836. p.cId = :course AND
  837. p.postParentId = :post AND
  838. p.threadId = :thread_of_deleted_post AND
  839. p.forumId = :forum_of_deleted_post
  840. ')
  841. ->execute([
  842. 'parent_of_deleted_post' => $post->getPostParentId(),
  843. 'course' => $course_id,
  844. 'post' => $post->getPostId(),
  845. 'thread_of_deleted_post' => $post->getThreadId(),
  846. 'forum_of_deleted_post' => $post->getForumId()
  847. ]);
  848. $em->remove($post);
  849. $em->flush();
  850. // Delete attachment file about this post id.
  851. delete_attachment($post_id);
  852. }
  853. $last_post_of_thread = check_if_last_post_of_thread($_GET['thread']);
  854. if (is_array($last_post_of_thread)) {
  855. // Decreasing the number of replies for this thread and also changing the last post information.
  856. $sql = "UPDATE $table_threads
  857. SET
  858. thread_replies = thread_replies - 1,
  859. thread_last_post = ".intval($last_post_of_thread['post_id']).",
  860. thread_date='".Database::escape_string($last_post_of_thread['post_date'])."'
  861. WHERE c_id = $course_id AND thread_id = ".intval($_GET['thread']);
  862. Database::query($sql);
  863. return 'PostDeleted';
  864. }
  865. if (!$last_post_of_thread) {
  866. // We deleted the very single post of the thread so we need to delete the entry in the thread table also.
  867. $sql = "DELETE FROM $table_threads
  868. WHERE c_id = $course_id AND thread_id = ".intval($_GET['thread']);
  869. Database::query($sql);
  870. return 'PostDeletedSpecial';
  871. }
  872. }
  873. /**
  874. * This function gets the all information of the last (=most recent) post of the thread
  875. * This can be done by sorting the posts that have the field thread_id=$thread_id and sort them by post_date
  876. *
  877. * @param $thread_id the id of the thread we want to know the last post of.
  878. * @return an array or bool if there is a last post found, false if there is
  879. * no post entry linked to that thread => thread will be deleted
  880. *
  881. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  882. * @version february 2006, dokeos 1.8
  883. */
  884. function check_if_last_post_of_thread($thread_id)
  885. {
  886. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  887. $course_id = api_get_course_int_id();
  888. $sql = "SELECT * FROM $table_posts
  889. WHERE c_id = $course_id AND thread_id = ".intval($thread_id)."
  890. ORDER BY post_date DESC";
  891. $result = Database::query($sql);
  892. if (Database::num_rows($result) > 0) {
  893. $row = Database::fetch_array($result);
  894. return $row;
  895. } else {
  896. return false;
  897. }
  898. }
  899. /**
  900. * @param $content what is it that we want to make (in)visible: forum category, forum, thread, post
  901. * @param $id the id of the content we want to make invisible
  902. * @param $current_visibility_status what is the current status of the visibility (0 = invisible, 1 = visible)
  903. * @param array $additional_url_parameters
  904. *
  905. * @return string HTML
  906. */
  907. function return_visible_invisible_icon($content, $id, $current_visibility_status, $additional_url_parameters = '')
  908. {
  909. $html = '';
  910. $id = Security::remove_XSS($id);
  911. if ($current_visibility_status == '1') {
  912. $html .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&';
  913. if (is_array($additional_url_parameters)) {
  914. foreach ($additional_url_parameters as $key => $value) {
  915. $html .= $key . '=' . $value . '&';
  916. }
  917. }
  918. $html.='action=invisible&content='.$content.'&id='.$id.'">'.
  919. Display::return_icon('visible.png', get_lang('MakeInvisible'), array(), ICON_SIZE_SMALL).'</a>';
  920. }
  921. if ($current_visibility_status == '0') {
  922. $html .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&';
  923. if (is_array($additional_url_parameters)) {
  924. foreach ($additional_url_parameters as $key => $value) {
  925. $html .= $key . '=' . $value . '&';
  926. }
  927. }
  928. $html .= 'action=visible&content=' . $content . '&id=' . $id . '">' .
  929. Display::return_icon('invisible.png', get_lang('MakeVisible'), array(), ICON_SIZE_SMALL) . '</a>';
  930. }
  931. return $html;
  932. }
  933. /**
  934. * @param $content
  935. * @param $id
  936. * @param $current_lock_status
  937. * @param string $additional_url_parameters
  938. * @return string
  939. */
  940. function return_lock_unlock_icon($content, $id, $current_lock_status, $additional_url_parameters = '')
  941. {
  942. $html = '';
  943. $id = intval($id);
  944. //check if the forum is blocked due
  945. if ($content == 'thread') {
  946. if (api_resource_is_locked_by_gradebook($id, LINK_FORUM_THREAD)) {
  947. $html .= Display::return_icon('lock_na.png', get_lang('ResourceLockedByGradebook'), array(), ICON_SIZE_SMALL);
  948. return $html;
  949. }
  950. }
  951. if ($current_lock_status == '1') {
  952. $html .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&';
  953. if (is_array($additional_url_parameters)) {
  954. foreach ($additional_url_parameters as $key => $value) {
  955. $html .= $key . '=' . $value . '&';
  956. }
  957. }
  958. $html.= 'action=unlock&content='.$content.'&id='.$id.'">'.
  959. Display::return_icon('lock.png', get_lang('Unlock'), array(), ICON_SIZE_SMALL).'</a>';
  960. }
  961. if ($current_lock_status == '0') {
  962. $html .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&';
  963. if (is_array($additional_url_parameters)) {
  964. foreach ($additional_url_parameters as $key => $value) {
  965. $html .= $key . '=' . $value . '&';
  966. }
  967. }
  968. $html .= 'action=lock&content=' . $content . '&id=' . $id . '">' .
  969. Display::return_icon('unlock.png', get_lang('Lock'), array(), ICON_SIZE_SMALL) . '</a>';
  970. }
  971. return $html;
  972. }
  973. /**
  974. * This function takes care of the display of the up and down icon
  975. *
  976. * @param $content what is it that we want to make (in)visible: forum category, forum, thread, post
  977. * @param $id is the id of the item we want to display the icons for
  978. * @param $list is an array of all the items. All items in this list should have
  979. * an up and down icon except for the first (no up icon) and the last (no down icon)
  980. * The key of this $list array is the id of the item.
  981. *
  982. * @return string HTML
  983. **/
  984. function return_up_down_icon($content, $id, $list)
  985. {
  986. $id = strval(intval($id));
  987. $total_items = count($list);
  988. $position = 0;
  989. $internal_counter = 0;
  990. $forumCategory = isset($_GET['forumcategory']) ? Security::remove_XSS($_GET['forumcategory']) : null;
  991. if (is_array($list)) {
  992. foreach ($list as $key => $listitem) {
  993. $internal_counter++;
  994. if ($id == $key) {
  995. $position = $internal_counter;
  996. }
  997. }
  998. }
  999. if ($position > 1) {
  1000. $return_value = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=move&direction=up&content='.$content.'&forumcategory='.$forumCategory.'&id='.$id.'" title="'.get_lang('MoveUp').'">'.
  1001. Display::return_icon('up.png', get_lang('MoveUp'), array(), ICON_SIZE_SMALL).'</a>';
  1002. } else {
  1003. $return_value = Display::return_icon('up_na.png', '-', array(), ICON_SIZE_SMALL);
  1004. }
  1005. if ($position < $total_items) {
  1006. $return_value .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=move&direction=down&content='.$content.'&forumcategory='.$forumCategory.'&id='.$id.'" title="'.get_lang('MoveDown').'" >'.
  1007. Display::return_icon('down.png', get_lang('MoveDown'), array(), ICON_SIZE_SMALL).'</a>';
  1008. } else {
  1009. $return_value .= Display::return_icon('down_na.png', '-', array(), ICON_SIZE_SMALL);
  1010. }
  1011. return $return_value;
  1012. }
  1013. /**
  1014. * This function changes the visibility in the database (item_property)
  1015. *
  1016. * @param string $content what is it that we want to make (in)visible: forum category, forum, thread, post
  1017. * @param int $id the id of the content we want to make invisible
  1018. * @param string $target_visibility what is the current status of the visibility (0 = invisible, 1 = visible)
  1019. *
  1020. * @todo change the get parameter so that it matches the tool constants.
  1021. * @todo check if api_item_property_update returns true or false => returnmessage depends on it.
  1022. * @todo move to itemmanager
  1023. *
  1024. * @return string language variable
  1025. *
  1026. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1027. * @version february 2006, dokeos 1.8
  1028. */
  1029. function change_visibility($content, $id, $target_visibility)
  1030. {
  1031. $_course = api_get_course_info();
  1032. $constants = array(
  1033. 'forumcategory' => TOOL_FORUM_CATEGORY,
  1034. 'forum' => TOOL_FORUM,
  1035. 'thread' => TOOL_FORUM_THREAD,
  1036. );
  1037. api_item_property_update(
  1038. $_course,
  1039. $constants[$content],
  1040. $id,
  1041. $target_visibility,
  1042. api_get_user_id()
  1043. );
  1044. if ($target_visibility == 'visible') {
  1045. handle_mail_cue($content, $id);
  1046. }
  1047. return get_lang('VisibilityChanged');
  1048. }
  1049. /**
  1050. * This function changes the lock status in the database
  1051. *
  1052. * @param string $content what is it that we want to (un)lock: forum category, forum, thread, post
  1053. * @param int $id the id of the content we want to (un)lock
  1054. * @param string $action do we lock (=>locked value in db = 1) or unlock (=> locked value in db = 0)
  1055. * @return string language variable
  1056. *
  1057. * @todo move to item manager
  1058. *
  1059. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1060. * @version february 2006, dokeos 1.8
  1061. */
  1062. function change_lock_status($content, $id, $action)
  1063. {
  1064. $table_categories = Database :: get_course_table(TABLE_FORUM_CATEGORY);
  1065. $table_forums = Database :: get_course_table(TABLE_FORUM);
  1066. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  1067. // Determine the relevant table.
  1068. if ($content == 'forumcategory') {
  1069. $table = $table_categories;
  1070. $id_field = 'cat_id';
  1071. } elseif ($content == 'forum') {
  1072. $table = $table_forums;
  1073. $id_field = 'forum_id';
  1074. } elseif ($content == 'thread') {
  1075. $table = $table_threads;
  1076. $id_field = 'thread_id';
  1077. } else {
  1078. return get_lang('Error');
  1079. }
  1080. // Determine what we are doing => defines the value for the database and the return message.
  1081. if ($action == 'lock') {
  1082. $db_locked = 1;
  1083. $return_message = get_lang('Locked');
  1084. } elseif ($action == 'unlock') {
  1085. $db_locked = 0;
  1086. $return_message = get_lang('Unlocked');
  1087. } else {
  1088. return get_lang('Error');
  1089. }
  1090. $course_id = api_get_course_int_id();
  1091. // Doing the change in the database
  1092. $sql = "UPDATE $table SET locked='".Database::escape_string($db_locked)."'
  1093. WHERE c_id = $course_id AND $id_field='".Database::escape_string($id)."'";
  1094. if (Database::query($sql)) {
  1095. return $return_message;
  1096. } else {
  1097. return get_lang('Error');
  1098. }
  1099. }
  1100. /**
  1101. * This function moves a forum or a forum category up or down
  1102. *
  1103. * @param $content what is it that we want to make (in)visible: forum category, forum, thread, post
  1104. * @param $direction do we want to move it up or down.
  1105. * @param $id the id of the content we want to make invisible
  1106. * @todo consider removing the table_item_property calls here but this can
  1107. * prevent unwanted side effects when a forum does not have an entry in
  1108. * the item_property table but does have one in the forum table.
  1109. * @return string language variable
  1110. *
  1111. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1112. * @version february 2006, dokeos 1.8
  1113. */
  1114. function move_up_down($content, $direction, $id)
  1115. {
  1116. $table_categories = Database:: get_course_table(TABLE_FORUM_CATEGORY);
  1117. $table_forums = Database:: get_course_table(TABLE_FORUM);
  1118. $table_item_property = Database:: get_course_table(TABLE_ITEM_PROPERTY);
  1119. $course_id = api_get_course_int_id();
  1120. $id = intval($id);
  1121. // Determine which field holds the sort order.
  1122. if ($content == 'forumcategory') {
  1123. $table = $table_categories;
  1124. $sort_column = 'cat_order';
  1125. $id_column = 'cat_id';
  1126. $sort_column = 'cat_order';
  1127. } elseif ($content == 'forum') {
  1128. $table = $table_forums;
  1129. $sort_column = 'forum_order';
  1130. $id_column = 'forum_id';
  1131. $sort_column = 'forum_order';
  1132. // We also need the forum_category of this forum.
  1133. $sql = "SELECT forum_category FROM $table_forums
  1134. WHERE c_id = $course_id AND forum_id = " . intval($id);
  1135. $result = Database::query($sql);
  1136. $row = Database::fetch_array($result);
  1137. $forum_category = $row['forum_category'];
  1138. } else {
  1139. return get_lang('Error');
  1140. }
  1141. // Determine the need for sorting ascending or descending order.
  1142. if ($direction == 'down') {
  1143. $sort_direction = 'ASC';
  1144. } elseif ($direction == 'up') {
  1145. $sort_direction = 'DESC';
  1146. } else {
  1147. return get_lang('Error');
  1148. }
  1149. // The SQL statement
  1150. if ($content == 'forumcategory') {
  1151. $sql = "SELECT *
  1152. FROM $table_categories forum_categories, $table_item_property item_properties
  1153. WHERE
  1154. forum_categories.c_id = $course_id AND
  1155. item_properties.c_id = $course_id AND
  1156. forum_categories.cat_id=item_properties.ref AND
  1157. item_properties.tool='" . TOOL_FORUM_CATEGORY . "'
  1158. ORDER BY forum_categories.cat_order $sort_direction";
  1159. }
  1160. if ($content == 'forum') {
  1161. $sql = "SELECT *
  1162. FROM $table
  1163. WHERE
  1164. c_id = $course_id AND
  1165. forum_category='" . Database::escape_string($forum_category) . "'
  1166. ORDER BY forum_order $sort_direction";
  1167. }
  1168. // Finding the items that need to be switched.
  1169. $result = Database::query($sql);
  1170. $found = false;
  1171. while ($row = Database::fetch_array($result)) {
  1172. //echo $row[$id_column].'-';
  1173. if ($found) {
  1174. $next_id = $row[$id_column];
  1175. $next_sort = $row[$sort_column];
  1176. $found = false;
  1177. }
  1178. if ($id == $row[$id_column]) {
  1179. $this_id = $id;
  1180. $this_sort = $row[$sort_column];
  1181. $found = true;
  1182. }
  1183. }
  1184. // Committing the switch.
  1185. // We do an extra check if we do not have illegal values. If your remove this if statment you will
  1186. // be able to mess with the sorting by refreshing the page over and over again.
  1187. if ($this_sort != '' && $next_sort != '' && $next_id != '' && $this_id != '') {
  1188. $sql = "UPDATE $table SET $sort_column='" . Database::escape_string($this_sort) . "'
  1189. WHERE c_id = $course_id AND $id_column='" . Database::escape_string($next_id) . "'";
  1190. Database::query($sql);
  1191. $sql = "UPDATE $table SET $sort_column='" . Database::escape_string($next_sort) . "'
  1192. WHERE c_id = $course_id AND $id_column='" . Database::escape_string($this_id) . "'";
  1193. Database::query($sql);
  1194. }
  1195. return get_lang(ucfirst($content) . 'Moved');
  1196. }
  1197. /**
  1198. * Retrieve all the information off the forum categories (or one specific) for the current course.
  1199. * The categories are sorted according to their sorting order (cat_order
  1200. *
  1201. * @param int|string $id default ''. When an id is passed we only find the information
  1202. * about that specific forum category. If no id is passed we get all the forum categories.
  1203. * @param int $courseId Optional. The course ID
  1204. * @param int $sessionId Optional. The session ID
  1205. * @return array containing all the information about all the forum categories
  1206. *
  1207. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1208. * @version february 2006, dokeos 1.8
  1209. */
  1210. function get_forum_categories($id = '', $courseId = 0, $sessionId = 0)
  1211. {
  1212. $table_categories = Database :: get_course_table(TABLE_FORUM_CATEGORY);
  1213. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  1214. // Condition for the session
  1215. $session_id = $sessionId ?: api_get_session_id();
  1216. $course_id = $courseId ?: api_get_course_int_id();
  1217. $condition_session = api_get_session_condition($session_id, true, true, 'forum_categories.session_id');
  1218. $condition_session .= " AND forum_categories.c_id = $course_id AND item_properties.c_id = $course_id";
  1219. if (empty($id)) {
  1220. $sql = "SELECT *
  1221. FROM $table_item_property item_properties
  1222. INNER JOIN $table_categories forum_categories
  1223. ON (
  1224. forum_categories.cat_id = item_properties.ref AND
  1225. item_properties.c_id = forum_categories.c_id
  1226. )
  1227. WHERE
  1228. item_properties.visibility = 1 AND
  1229. item_properties.tool = '".TOOL_FORUM_CATEGORY."'
  1230. $condition_session
  1231. ORDER BY forum_categories.cat_order ASC";
  1232. if (api_is_allowed_to_edit()) {
  1233. $sql = "SELECT *
  1234. FROM $table_item_property item_properties
  1235. INNER JOIN $table_categories forum_categories
  1236. ON (
  1237. forum_categories.cat_id = item_properties.ref AND
  1238. item_properties.c_id = forum_categories.c_id
  1239. )
  1240. WHERE
  1241. item_properties.visibility<>2 AND
  1242. item_properties.tool='".TOOL_FORUM_CATEGORY."'
  1243. $condition_session
  1244. ORDER BY forum_categories.cat_order ASC";
  1245. }
  1246. } else {
  1247. $sql = "SELECT *
  1248. FROM $table_item_property item_properties
  1249. INNER JOIN $table_categories forum_categories
  1250. ON (
  1251. forum_categories.cat_id = item_properties.ref AND
  1252. item_properties.c_id = forum_categories.c_id
  1253. )
  1254. WHERE
  1255. item_properties.tool='".TOOL_FORUM_CATEGORY."' AND
  1256. forum_categories.cat_id = ".intval($id)."
  1257. $condition_session
  1258. ORDER BY forum_categories.cat_order ASC";
  1259. }
  1260. $result = Database::query($sql);
  1261. $forum_categories_list = array();
  1262. while ($row = Database::fetch_assoc($result)) {
  1263. if (empty($id)) {
  1264. $forum_categories_list[$row['cat_id']] = $row;
  1265. } else {
  1266. $forum_categories_list = $row;
  1267. }
  1268. }
  1269. return $forum_categories_list;
  1270. }
  1271. /**
  1272. * This function retrieves all the fora in a given forum category
  1273. *
  1274. * @param int $cat_id the id of the forum category
  1275. * @param int $courseId Optional. The course ID
  1276. * @return array containing all the information about the forums (regardless of their category)
  1277. *
  1278. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1279. * @version february 2006, dokeos 1.8
  1280. */
  1281. function get_forums_in_category($cat_id, $courseId = 0)
  1282. {
  1283. $table_forums = Database::get_course_table(TABLE_FORUM);
  1284. $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1285. $forum_list = array();
  1286. $course_id = $courseId ?: api_get_course_int_id();
  1287. $cat_id = (int) $cat_id;
  1288. $sql = "SELECT * FROM $table_forums forum
  1289. INNER JOIN $table_item_property item_properties
  1290. ON (forum.forum_id = item_properties.ref AND item_properties.c_id = forum.c_id)
  1291. WHERE
  1292. forum.forum_category = '".$cat_id."' AND
  1293. item_properties.visibility = 1 AND
  1294. forum.c_id = $course_id AND
  1295. item_properties.c_id = $course_id AND
  1296. item_properties.tool = '".TOOL_FORUM."'
  1297. ORDER BY forum.forum_order ASC";
  1298. if (api_is_allowed_to_edit()) {
  1299. $sql = "SELECT * FROM $table_forums forum
  1300. INNER JOIN $table_item_property item_properties
  1301. ON (forum.forum_id = item_properties.ref AND item_properties.c_id = forum.c_id)
  1302. WHERE
  1303. forum.forum_category = '".$cat_id."' AND
  1304. item_properties.visibility <> 2 AND
  1305. item_properties.tool = '".TOOL_FORUM."' AND
  1306. item_properties.c_id = $course_id AND
  1307. forum.c_id = $course_id
  1308. ORDER BY forum_order ASC";
  1309. }
  1310. $result = Database::query($sql);
  1311. while ($row = Database::fetch_array($result)) {
  1312. $forum_list[$row['forum_id']] = $row;
  1313. }
  1314. return $forum_list;
  1315. }
  1316. /**
  1317. * Retrieve all the forums (regardless of their category) or of only one.
  1318. * The forums are sorted according to the forum_order.
  1319. * Since it does not take the forum category into account there probably
  1320. * will be two or more forums that have forum_order=1, ...
  1321. * @param int $id forum id
  1322. * @param string $course_code
  1323. * @param bool $includeGroupsForum
  1324. * @param int $sessionId
  1325. * @return array an array containing all the information about the forums (regardless of their category)
  1326. * @todo check $sql4 because this one really looks fishy.
  1327. *
  1328. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1329. * @version february 2006, dokeos 1.8
  1330. */
  1331. function get_forums(
  1332. $id = '',
  1333. $course_code = '',
  1334. $includeGroupsForum = true,
  1335. $sessionId = 0
  1336. ) {
  1337. $course_info = api_get_course_info($course_code);
  1338. $table_forums = Database::get_course_table(TABLE_FORUM);
  1339. $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
  1340. $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1341. // Condition for the session
  1342. $session_id = intval($sessionId) ?: api_get_session_id();
  1343. $sessionIdLink = $session_id === 0 ? '' : ' AND threads.session_id = item_properties.session_id';
  1344. $condition_session = api_get_session_condition(
  1345. $session_id,
  1346. true,
  1347. false,
  1348. 'item_properties.session_id'
  1349. );
  1350. $course_id = $course_info['real_id'];
  1351. $forum_list = array();
  1352. $includeGroupsForumSelect = '';
  1353. if (!$includeGroupsForum) {
  1354. $includeGroupsForumSelect = " AND forum_of_group = 0 ";
  1355. }
  1356. if ($id == '') {
  1357. // Student
  1358. // Select all the forum information of all forums (that are visible to students).
  1359. $sql = "SELECT item_properties.*, forum.*
  1360. FROM $table_forums forum
  1361. INNER JOIN $table_item_property item_properties
  1362. ON (
  1363. forum.forum_id = item_properties.ref AND
  1364. forum.c_id = item_properties.c_id
  1365. )
  1366. WHERE
  1367. item_properties.visibility = 1 AND
  1368. item_properties.tool = '".TOOL_FORUM."'
  1369. $condition_session AND
  1370. forum.c_id = $course_id AND
  1371. item_properties.c_id = $course_id
  1372. $includeGroupsForumSelect
  1373. ORDER BY forum.forum_order ASC";
  1374. // Select the number of threads of the forums (only the threads that are visible).
  1375. $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id
  1376. FROM $table_threads threads
  1377. INNER JOIN $table_item_property item_properties
  1378. ON (
  1379. threads.thread_id = item_properties.ref AND
  1380. threads.c_id = item_properties.c_id
  1381. $sessionIdLink
  1382. )
  1383. WHERE
  1384. item_properties.visibility=1 AND
  1385. item_properties.tool='".TOOL_FORUM_THREAD."' AND
  1386. threads.c_id = $course_id AND
  1387. item_properties.c_id = $course_id
  1388. GROUP BY threads.forum_id";
  1389. // Course Admin
  1390. if (api_is_allowed_to_edit()) {
  1391. // Select all the forum information of all forums (that are not deleted).
  1392. $sql = "SELECT item_properties.*, forum.*
  1393. FROM $table_forums forum
  1394. INNER JOIN $table_item_property item_properties
  1395. ON (
  1396. forum.forum_id = item_properties.ref AND
  1397. forum.c_id = item_properties.c_id
  1398. )
  1399. WHERE
  1400. item_properties.visibility <> 2 AND
  1401. item_properties.tool = '".TOOL_FORUM."'
  1402. $condition_session AND
  1403. forum.c_id = $course_id AND
  1404. item_properties.c_id = $course_id
  1405. $includeGroupsForumSelect
  1406. ORDER BY forum_order ASC";
  1407. // Select the number of threads of the forums (only the threads that are not deleted).
  1408. $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id
  1409. FROM $table_threads threads
  1410. INNER JOIN $table_item_property item_properties
  1411. ON (
  1412. threads.thread_id = item_properties.ref AND
  1413. threads.c_id = item_properties.c_id
  1414. $sessionIdLink
  1415. )
  1416. WHERE
  1417. item_properties.visibility<>2 AND
  1418. item_properties.tool='".TOOL_FORUM_THREAD."' AND
  1419. threads.c_id = $course_id AND
  1420. item_properties.c_id = $course_id
  1421. GROUP BY threads.forum_id";
  1422. }
  1423. } else {
  1424. // GETTING ONE SPECIFIC FORUM
  1425. /* We could do the splitup into student and course admin also but we want
  1426. to have as much as information about a certain forum as possible
  1427. so we do not take too much information into account. This function
  1428. (or this section of the function) is namely used to fill the forms
  1429. when editing a forum (and for the moment it is the only place where
  1430. we use this part of the function) */
  1431. // Select all the forum information of the given forum (that is not deleted).
  1432. $sql = "SELECT * FROM $table_item_property item_properties
  1433. INNER JOIN $table_forums forum
  1434. ON (forum.forum_id = item_properties.ref AND forum.c_id = item_properties.c_id)
  1435. WHERE
  1436. forum.forum_id = " . intval($id) . " AND
  1437. forum.c_id = $course_id AND
  1438. item_properties.visibility != 2 AND
  1439. item_properties.tool = '".TOOL_FORUM."'
  1440. ORDER BY forum_order ASC";
  1441. // Select the number of threads of the forum.
  1442. $sql2 = "SELECT count(*) AS number_of_threads, forum_id
  1443. FROM $table_threads
  1444. WHERE
  1445. forum_id = " . intval($id) . "
  1446. GROUP BY forum_id";
  1447. }
  1448. // Handling all the forum information.
  1449. $result = Database::query($sql);
  1450. while ($row = Database::fetch_assoc($result)) {
  1451. if ($id == '') {
  1452. $forum_list[$row['forum_id']] = $row;
  1453. } else {
  1454. $forum_list = $row;
  1455. }
  1456. }
  1457. // Handling the thread count information.
  1458. $result2 = Database::query($sql2);
  1459. while ($row2 = Database::fetch_array($result2)) {
  1460. if ($id == '') {
  1461. $forum_list[$row2['forum_id']]['number_of_threads'] = $row2['number_of_threads'];
  1462. } else {
  1463. $forum_list['number_of_threads'] = $row2['number_of_threads'];
  1464. }
  1465. }
  1466. /* Finding the last post information
  1467. (last_post_id, last_poster_id, last_post_date, last_poster_name, last_poster_lastname, last_poster_firstname)*/
  1468. if ($id == '') {
  1469. if (is_array($forum_list)) {
  1470. foreach ($forum_list as $key => $value) {
  1471. $last_post_info_of_forum = get_last_post_information(
  1472. $key,
  1473. api_is_allowed_to_edit(),
  1474. $course_id
  1475. );
  1476. if ($last_post_info_of_forum) {
  1477. $forum_list[$key]['last_post_id'] = $last_post_info_of_forum['last_post_id'];
  1478. $forum_list[$key]['last_poster_id'] = $last_post_info_of_forum['last_poster_id'];
  1479. $forum_list[$key]['last_post_date'] = $last_post_info_of_forum['last_post_date'];
  1480. $forum_list[$key]['last_poster_name'] = $last_post_info_of_forum['last_poster_name'];
  1481. $forum_list[$key]['last_poster_lastname'] = $last_post_info_of_forum['last_poster_lastname'];
  1482. $forum_list[$key]['last_poster_firstname'] = $last_post_info_of_forum['last_poster_firstname'];
  1483. }
  1484. }
  1485. } else {
  1486. $forum_list = array();
  1487. }
  1488. } else {
  1489. $last_post_info_of_forum = get_last_post_information(
  1490. $id,
  1491. api_is_allowed_to_edit(),
  1492. $course_id
  1493. );
  1494. if ($last_post_info_of_forum) {
  1495. $forum_list['last_post_id'] = $last_post_info_of_forum['last_post_id'];
  1496. $forum_list['last_poster_id'] = $last_post_info_of_forum['last_poster_id'];
  1497. $forum_list['last_post_date'] = $last_post_info_of_forum['last_post_date'];
  1498. $forum_list['last_poster_name'] = $last_post_info_of_forum['last_poster_name'];
  1499. $forum_list['last_poster_lastname'] = $last_post_info_of_forum['last_poster_lastname'];
  1500. $forum_list['last_poster_firstname'] = $last_post_info_of_forum['last_poster_firstname'];
  1501. }
  1502. }
  1503. return $forum_list;
  1504. }
  1505. /**
  1506. * @param int $course_id
  1507. * @param int $thread_id
  1508. * @param int $forum_id
  1509. * @param bool $show_visible
  1510. * @return array|bool
  1511. */
  1512. function get_last_post_by_thread($course_id, $thread_id, $forum_id, $show_visible = true)
  1513. {
  1514. if (empty($thread_id) || empty($forum_id) || empty($course_id)) {
  1515. return false;
  1516. }
  1517. $thread_id = intval($thread_id);
  1518. $forum_id = intval($forum_id);
  1519. $course_id = intval($course_id);
  1520. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  1521. $sql = "SELECT * FROM $table_posts
  1522. WHERE
  1523. c_id = $course_id AND
  1524. thread_id = $thread_id AND
  1525. forum_id = $forum_id";
  1526. if ($show_visible == false) {
  1527. $sql .= " AND visible = 1 ";
  1528. }
  1529. $sql .= " ORDER BY post_id DESC LIMIT 1";
  1530. $result = Database::query($sql);
  1531. if (Database::num_rows($result)) {
  1532. return Database::fetch_array($result, 'ASSOC');
  1533. } else {
  1534. return false;
  1535. }
  1536. }
  1537. /**
  1538. * This function gets all the last post information of a certain forum
  1539. *
  1540. * @param int $forum_id the id of the forum we want to know the last post information of.
  1541. * @param bool $show_invisibles
  1542. * @param string course db name
  1543. * @return array containing all the information about the last post
  1544. * (last_post_id, last_poster_id, last_post_date, last_poster_name, last_poster_lastname, last_poster_firstname)
  1545. *
  1546. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1547. * @version february 2006, dokeos 1.8
  1548. */
  1549. function get_last_post_information($forum_id, $show_invisibles = false, $course_id = null)
  1550. {
  1551. if (!isset($course_id)) {
  1552. $course_id = api_get_course_int_id();
  1553. } else {
  1554. $course_id = intval($course_id);
  1555. }
  1556. $sessionId = api_get_session_id();
  1557. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  1558. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  1559. $table_users = Database :: get_main_table(TABLE_MAIN_USER);
  1560. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  1561. $forum_id = intval($forum_id);
  1562. $return_array = array();
  1563. // First get the threads to make sure there is no inconsistency in the
  1564. // database between forum and thread
  1565. $sql = "SELECT thread_id FROM $table_threads
  1566. WHERE
  1567. forum_id = $forum_id AND
  1568. c_id = $course_id AND
  1569. session_id = $sessionId";
  1570. $result = Database::query($sql);
  1571. if (Database::num_rows($result) == 0) {
  1572. // If there are no threads in this forum, then there are no posts
  1573. return [];
  1574. }
  1575. $threads = array();
  1576. while ($row = Database::fetch_row($result)) {
  1577. $threads[] = $row[0];
  1578. }
  1579. $threadsList = implode(',', $threads);
  1580. // Now get the posts that are linked to these threads
  1581. $sql = "SELECT
  1582. post.post_id,
  1583. post.forum_id,
  1584. post.poster_id,
  1585. post.poster_name,
  1586. post.post_date,
  1587. users.lastname,
  1588. users.firstname,
  1589. post.visible,
  1590. thread_properties.visibility AS thread_visibility,
  1591. forum_properties.visibility AS forum_visibility
  1592. FROM
  1593. $table_posts post,
  1594. $table_users users,
  1595. $table_item_property thread_properties,
  1596. $table_item_property forum_properties
  1597. WHERE
  1598. post.forum_id = $forum_id
  1599. AND post.thread_id IN ($threadsList)
  1600. AND post.poster_id = users.user_id
  1601. AND post.thread_id = thread_properties.ref
  1602. AND thread_properties.tool='".TOOL_FORUM_THREAD."'
  1603. AND post.forum_id=forum_properties.ref
  1604. AND forum_properties.tool='".TOOL_FORUM."'
  1605. AND post.c_id = $course_id AND
  1606. thread_properties.c_id = $course_id AND
  1607. forum_properties.c_id = $course_id
  1608. ORDER BY post.post_id DESC";
  1609. $result = Database::query($sql);
  1610. if ($show_invisibles) {
  1611. $row = Database::fetch_array($result);
  1612. $return_array['last_post_id'] = $row['post_id'];
  1613. $return_array['last_poster_id'] = $row['poster_id'];
  1614. $return_array['last_post_date'] = $row['post_date'];
  1615. $return_array['last_poster_name'] = $row['poster_name'];
  1616. $return_array['last_poster_lastname'] = $row['lastname'];
  1617. $return_array['last_poster_firstname'] = $row['firstname'];
  1618. return $return_array;
  1619. } else {
  1620. // We have to loop through the results to find the first one that is
  1621. // actually visible to students (forum_category, forum, thread AND post are visible).
  1622. while ($row = Database::fetch_array($result)) {
  1623. if ($row['visible'] == '1' && $row['thread_visibility'] == '1' && $row['forum_visibility'] == '1') {
  1624. $return_array['last_post_id'] = $row['post_id'];
  1625. $return_array['last_poster_id'] = $row['poster_id'];
  1626. $return_array['last_post_date'] = $row['post_date'];
  1627. $return_array['last_poster_name'] = $row['poster_name'];
  1628. $return_array['last_poster_lastname'] = $row['lastname'];
  1629. $return_array['last_poster_firstname'] = $row['firstname'];
  1630. return $return_array;
  1631. }
  1632. }
  1633. }
  1634. }
  1635. /**
  1636. * Retrieve all the threads of a given forum
  1637. *
  1638. * @param int $forum_id
  1639. * @param int|null $courseId Optional If is null then it is considered the current course
  1640. * @param int|null $sessionId Optional. If is null then it is considered the current session
  1641. * @return array containing all the information about the threads
  1642. *
  1643. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1644. * @version february 2006, dokeos 1.8
  1645. */
  1646. function get_threads($forum_id, $courseId = null, $sessionId = null)
  1647. {
  1648. $groupId = api_get_group_id();
  1649. $sessionId = $sessionId !== null ? intval($sessionId) : api_get_session_id();
  1650. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  1651. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  1652. $table_users = Database :: get_main_table(TABLE_MAIN_USER);
  1653. $courseId = $courseId !== null ? intval($courseId) : api_get_course_int_id();
  1654. $groupInfo = GroupManager::get_group_properties($groupId);
  1655. $groupCondition = '';
  1656. if (!empty($groupInfo)) {
  1657. $groupIid = $groupInfo['iid'];
  1658. $groupCondition = " AND item_properties.to_group_id = '$groupIid' ";
  1659. }
  1660. $sessionCondition = api_get_session_condition($sessionId, true, false, 'item_properties.session_id');
  1661. // important note: it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
  1662. // because we also have thread.* in it. This is because thread has a field locked and post also has the same field
  1663. // since we are merging these we would have the post.locked value but in fact we want the thread.locked value
  1664. // This is why it is added to the end of the field selection
  1665. $sql = "SELECT DISTINCT
  1666. item_properties.*,
  1667. users.firstname,
  1668. users.lastname,
  1669. users.user_id,
  1670. thread.locked as locked,
  1671. thread.*
  1672. FROM $table_threads thread
  1673. INNER JOIN $table_item_property item_properties
  1674. ON
  1675. thread.thread_id = item_properties.ref AND
  1676. item_properties.c_id = thread.c_id AND
  1677. item_properties.tool = '".TABLE_FORUM_THREAD."'
  1678. $groupCondition
  1679. $sessionCondition
  1680. LEFT JOIN $table_users users
  1681. ON thread.thread_poster_id = users.user_id
  1682. WHERE
  1683. item_properties.visibility='1' AND
  1684. thread.forum_id = ".intval($forum_id)." AND
  1685. thread.c_id = $courseId
  1686. ORDER BY thread.thread_sticky DESC, thread.thread_date DESC";
  1687. if (api_is_allowed_to_edit()) {
  1688. $sql = "SELECT DISTINCT
  1689. item_properties.*,
  1690. users.firstname,
  1691. users.lastname,
  1692. users.user_id,
  1693. thread.locked as locked,
  1694. thread.*
  1695. FROM $table_threads thread
  1696. INNER JOIN $table_item_property item_properties
  1697. ON
  1698. thread.thread_id = item_properties.ref AND
  1699. item_properties.c_id = thread.c_id AND
  1700. item_properties.tool = '".TABLE_FORUM_THREAD."'
  1701. $groupCondition
  1702. $sessionCondition
  1703. LEFT JOIN $table_users users
  1704. ON thread.thread_poster_id=users.user_id
  1705. WHERE
  1706. item_properties.visibility<>2 AND
  1707. thread.forum_id = ".intval($forum_id)." AND
  1708. thread.c_id = $courseId
  1709. ORDER BY thread.thread_sticky DESC, thread.thread_date DESC";
  1710. }
  1711. $result = Database::query($sql);
  1712. $list = array();
  1713. $alreadyAdded = array();
  1714. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1715. if (in_array($row['thread_id'], $alreadyAdded)) {
  1716. continue;
  1717. }
  1718. $list[] = $row;
  1719. $alreadyAdded[] = $row['thread_id'];
  1720. }
  1721. return $list;
  1722. }
  1723. /**
  1724. * Get a thread by Id and course id
  1725. *
  1726. * @param int $threadId the thread Id
  1727. * @param int $cId the course id
  1728. * @return array containing all the information about the thread
  1729. */
  1730. function getThreadInfo($threadId, $cId)
  1731. {
  1732. $em = Database::getManager();
  1733. $forumThread = $em->getRepository('ChamiloCourseBundle:CForumThread')->findOneBy(['threadId' => $threadId, 'cId' => $cId]);
  1734. $thread = [];
  1735. if ($forumThread) {
  1736. $thread['threadId'] = $forumThread->getThreadId();
  1737. $thread['threadTitle'] = $forumThread->getThreadTitle();
  1738. $thread['forumId'] = $forumThread->getForumId();
  1739. $thread['sessionId'] = $forumThread->getSessionId();
  1740. $thread['threadSticky'] = $forumThread->getThreadSticky();
  1741. $thread['locked'] = $forumThread->getLocked();
  1742. $thread['threadTitleQualify'] = $forumThread->getThreadTitleQualify();
  1743. $thread['threadQualifyMax'] = $forumThread->getThreadQualifyMax();
  1744. $thread['threadCloseDate'] = $forumThread->getThreadCloseDate();
  1745. $thread['threadWeight'] = $forumThread->getThreadWeight();
  1746. $thread['threadPeerQualify'] = $forumThread->isThreadPeerQualify();
  1747. }
  1748. return $thread;
  1749. }
  1750. /**
  1751. * Retrieve all posts of a given thread
  1752. * @param array $forumInfo
  1753. * @param int $threadId The thread ID
  1754. * @param string $orderDirection Optional. The direction for sort the posts
  1755. * @param boolean $recursive Optional. If the list is recursive
  1756. * @param int $postId Optional. The post ID for recursive list
  1757. * @param int $depth Optional. The depth to indicate the indent
  1758. * @todo move to a repository
  1759. *
  1760. * @return array containing all the information about the posts of a given thread
  1761. */
  1762. function getPosts(
  1763. $forumInfo,
  1764. $threadId,
  1765. $orderDirection = 'ASC',
  1766. $recursive = false,
  1767. $postId = null,
  1768. $depth = -1
  1769. ) {
  1770. $em = Database::getManager();
  1771. if (api_is_allowed_to_edit(false, true)) {
  1772. $visibleCriteria = Criteria::expr()->neq('visible', 2);
  1773. } else {
  1774. $visibleCriteria = Criteria::expr()->eq('visible', 1);
  1775. }
  1776. $criteria = Criteria::create();
  1777. $criteria
  1778. ->where(Criteria::expr()->eq('threadId', $threadId))
  1779. ->andWhere(Criteria::expr()->eq('cId', $forumInfo['c_id']))
  1780. ->andWhere($visibleCriteria)
  1781. ;
  1782. $groupId = api_get_group_id();
  1783. $groupInfo = GroupManager::get_group_properties($groupId);
  1784. $filterModerated = true;
  1785. if (empty($groupId)) {
  1786. if (api_is_allowed_to_edit()) {
  1787. $filterModerated = false;
  1788. }
  1789. } else {
  1790. if (GroupManager::is_tutor_of_group(api_get_user_id(), $groupInfo['iid']) || api_is_allowed_to_edit(false, true)) {
  1791. $filterModerated = false;
  1792. }
  1793. }
  1794. if ($recursive) {
  1795. $criteria->andWhere(Criteria::expr()->eq('postParentId', $postId));
  1796. }
  1797. $qb = $em->getRepository('ChamiloCourseBundle:CForumPost')->createQueryBuilder('p');
  1798. $qb->select('p')
  1799. ->addCriteria($criteria)
  1800. ->addOrderBy('p.postId', $orderDirection);
  1801. if ($filterModerated && $forumInfo['moderated'] == 1) {
  1802. if (!api_is_allowed_to_edit(false, true)) {
  1803. $userId = api_get_user_id();
  1804. $qb->andWhere(
  1805. "p.status = 1 OR
  1806. (p.status = ".CForumPost::STATUS_WAITING_MODERATION." AND p.posterId = $userId) OR
  1807. (p.status IS NULL AND p.posterId = $userId)
  1808. "
  1809. );
  1810. }
  1811. }
  1812. $posts = $qb->getQuery()->getResult();
  1813. $depth++;
  1814. $list = [];
  1815. /** @var CForumPost $post */
  1816. foreach ($posts as $post) {
  1817. $postInfo = [
  1818. 'iid' => $post->getIid(),
  1819. 'c_id' => $post->getCId(),
  1820. 'post_id' => $post->getPostId(),
  1821. 'post_title' => $post->getPostTitle(),
  1822. 'post_text' => $post->getPostText(),
  1823. 'thread_id' => $post->getThreadId(),
  1824. 'forum_id' => $post->getForumId(),
  1825. 'poster_id' => $post->getPosterId(),
  1826. 'poster_name' => $post->getPosterName(),
  1827. 'post_date' => $post->getPostDate(),
  1828. 'post_notification' => $post->getPostNotification(),
  1829. 'post_parent_id' => $post->getPostParentId(),
  1830. 'visible' => $post->getVisible(),
  1831. 'status' => $post->getStatus(),
  1832. 'indent_cnt' => $depth
  1833. ];
  1834. $posterId = $post->getPosterId();
  1835. if (!empty($posterId)) {
  1836. $user = $em->find('ChamiloUserBundle:User', $posterId);
  1837. if ($user) {
  1838. $postInfo['user_id'] = $user->getUserId();
  1839. $postInfo['username'] = $user->getUsername();
  1840. $postInfo['username_canonical'] = $user->getUsernameCanonical();
  1841. $postInfo['lastname'] = $user->getLastname();
  1842. $postInfo['firstname'] = $user->getFirstname();
  1843. }
  1844. }
  1845. $list[] = $postInfo;
  1846. if (!$recursive) {
  1847. continue;
  1848. }
  1849. $list = array_merge(
  1850. $list,
  1851. getPosts(
  1852. $forumInfo,
  1853. $threadId,
  1854. $orderDirection,
  1855. $recursive,
  1856. $post->getPostId(),
  1857. $depth
  1858. )
  1859. );
  1860. }
  1861. return $list;
  1862. }
  1863. /**
  1864. * This function retrieves all the information of a post
  1865. *
  1866. * @param int $post_id integer that indicates the forum
  1867. *
  1868. * @return array returns
  1869. *
  1870. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1871. * @version february 2006, dokeos 1.8
  1872. */
  1873. function get_post_information($post_id)
  1874. {
  1875. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  1876. $table_users = Database :: get_main_table(TABLE_MAIN_USER);
  1877. $course_id = api_get_course_int_id();
  1878. $sql = "SELECT posts.*, email FROM ".$table_posts." posts, ".$table_users." users
  1879. WHERE
  1880. c_id = $course_id AND
  1881. posts.poster_id=users.user_id AND
  1882. posts.post_id = ".intval($post_id);
  1883. $result = Database::query($sql);
  1884. $row = Database::fetch_array($result, 'ASSOC');
  1885. return $row;
  1886. }
  1887. /**
  1888. * This function retrieves all the information of a thread
  1889. *
  1890. * @param int $forumId
  1891. * @param $thread_id integer that indicates the forum
  1892. * @param int|null $sessionId Optional. If is null then it is considered the current session
  1893. * @return array returns
  1894. *
  1895. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1896. * @version february 2006, dokeos 1.8
  1897. */
  1898. function get_thread_information($forumId, $thread_id, $sessionId = null)
  1899. {
  1900. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  1901. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  1902. $thread_id = intval($thread_id);
  1903. $sessionId = $sessionId !== null ? intval($sessionId) : api_get_session_id();
  1904. $sessionCondition = api_get_session_condition($sessionId, true, false, 'threads.session_id');
  1905. $forumCondition = '';
  1906. if (!empty($forumId)) {
  1907. $forumId = (int) $forumId;
  1908. $forumCondition = " threads.forum_id = $forumId AND ";
  1909. }
  1910. $sql = "SELECT * FROM $table_item_property item_properties
  1911. INNER JOIN
  1912. $table_threads threads
  1913. ON (item_properties.ref = threads.thread_id AND threads.c_id = item_properties.c_id)
  1914. WHERE
  1915. $forumCondition
  1916. item_properties.tool= '".TOOL_FORUM_THREAD."' AND
  1917. threads.thread_id = $thread_id
  1918. $sessionCondition
  1919. ";
  1920. $result = Database::query($sql);
  1921. $row = Database::fetch_assoc($result);
  1922. return $row;
  1923. }
  1924. /**
  1925. * This function retrieves forum thread users details
  1926. * @param int Thread ID
  1927. * @param string Course DB name (optional)
  1928. * @return Doctrine\DBAL\Driver\Statement|null array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  1929. * @author Christian Fasanando <christian.fasanando@dokeos.com>,
  1930. * @todo this function need to be improved
  1931. * @version octubre 2008, dokeos 1.8
  1932. */
  1933. function get_thread_users_details($thread_id)
  1934. {
  1935. $t_posts = Database :: get_course_table(TABLE_FORUM_POST);
  1936. $t_users = Database :: get_main_table(TABLE_MAIN_USER);
  1937. $t_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1938. $t_session_rel_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1939. $course_id = api_get_course_int_id();
  1940. $is_western_name_order = api_is_western_name_order();
  1941. if ($is_western_name_order) {
  1942. $orderby = 'ORDER BY user.firstname, user.lastname ';
  1943. } else {
  1944. $orderby = 'ORDER BY user.lastname, user.firstname';
  1945. }
  1946. if (api_get_session_id()) {
  1947. $session_info = api_get_session_info(api_get_session_id());
  1948. $user_to_avoid = "'".$session_info['id_coach']."', '".$session_info['session_admin_id']."'";
  1949. //not showing coaches
  1950. $sql = "SELECT DISTINCT user.id, user.lastname, user.firstname, thread_id
  1951. FROM $t_posts p, $t_users user, $t_session_rel_user session_rel_user_rel_course
  1952. WHERE p.poster_id = user.id AND
  1953. user.id = session_rel_user_rel_course.user_id AND
  1954. session_rel_user_rel_course.status<>'2' AND
  1955. session_rel_user_rel_course.user_id NOT IN ($user_to_avoid) AND
  1956. p.thread_id = ".intval($thread_id)." AND
  1957. session_id = ".api_get_session_id()." AND
  1958. p.c_id = $course_id AND
  1959. session_rel_user_rel_course.c_id = ".$course_id." $orderby ";
  1960. } else {
  1961. $sql = "SELECT DISTINCT user.id, user.lastname, user.firstname, thread_id
  1962. FROM $t_posts p, $t_users user, $t_course_user course_user
  1963. WHERE p.poster_id = user.id
  1964. AND user.id = course_user.user_id
  1965. AND course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  1966. AND p.thread_id = ".intval($thread_id)."
  1967. AND course_user.status NOT IN('1') AND
  1968. p.c_id = $course_id AND
  1969. course_user.c_id = ".$course_id." $orderby";
  1970. }
  1971. $result = Database::query($sql);
  1972. return $result;
  1973. }
  1974. /**
  1975. * This function retrieves forum thread users qualify
  1976. * @param int Thread ID
  1977. * @param string Course DB name (optional)
  1978. * @return Doctrine\DBAL\Driver\Statement|null Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  1979. * @author Jhon Hinojosa
  1980. * @todo this function need to be improved
  1981. */
  1982. function get_thread_users_qualify($thread_id)
  1983. {
  1984. $t_posts = Database :: get_course_table(TABLE_FORUM_POST);
  1985. $t_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  1986. $t_users = Database :: get_main_table(TABLE_MAIN_USER);
  1987. $t_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1988. $t_session_rel_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1989. $course_id = api_get_course_int_id();
  1990. $sessionId = api_get_session_id();
  1991. $is_western_name_order = api_is_western_name_order();
  1992. if ($is_western_name_order) {
  1993. $orderby = 'ORDER BY user.firstname, user.lastname ';
  1994. } else {
  1995. $orderby = 'ORDER BY user.lastname, user.firstname';
  1996. }
  1997. if ($sessionId) {
  1998. $session_info = api_get_session_info($sessionId);
  1999. $user_to_avoid = "'".$session_info['id_coach']."', '".$session_info['session_admin_id']."'";
  2000. //not showing coaches
  2001. $sql = "SELECT DISTINCT post.poster_id, user.lastname, user.firstname, post.thread_id,user.id,qualify.qualify
  2002. FROM $t_posts post , $t_users user, $t_session_rel_user scu, $t_qualify qualify
  2003. WHERE poster_id = user.id
  2004. AND post.poster_id = qualify.user_id
  2005. AND user.id = scu.user_id
  2006. AND scu.status<>'2'
  2007. AND scu.user_id NOT IN ($user_to_avoid)
  2008. AND qualify.thread_id = ".intval($thread_id)."
  2009. AND post.thread_id = ".intval($thread_id)."
  2010. AND scu.session_id = $sessionId
  2011. AND scu.c_id = ".$course_id." AND
  2012. qualify.c_id = $course_id AND
  2013. post.c_id = $course_id
  2014. $orderby ";
  2015. } else {
  2016. $sql = "SELECT DISTINCT post.poster_id, user.lastname, user.firstname, post.thread_id,user.id,qualify.qualify
  2017. FROM $t_posts post,
  2018. $t_qualify qualify,
  2019. $t_users user,
  2020. $t_course_user course_user
  2021. WHERE
  2022. post.poster_id = user.id
  2023. AND post.poster_id = qualify.user_id
  2024. AND user.id = course_user.user_id
  2025. AND course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  2026. AND qualify.thread_id = ".intval($thread_id)."
  2027. AND post.thread_id = ".intval($thread_id)."
  2028. AND course_user.status not in('1')
  2029. AND course_user.c_id = $course_id
  2030. AND qualify.c_id = $course_id
  2031. AND post.c_id = $course_id
  2032. $orderby ";
  2033. }
  2034. $result = Database::query($sql);
  2035. return $result;
  2036. }
  2037. /**
  2038. * This function retrieves forum thread users not qualify
  2039. * @param int Thread ID
  2040. * @param string Course DB name (optional)
  2041. * @return Doctrine\DBAL\Driver\Statement|null Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  2042. * @author Jhon Hinojosa<jhon.hinojosa@dokeos.com>,
  2043. * @version oct 2008, dokeos 1.8
  2044. */
  2045. function get_thread_users_not_qualify($thread_id)
  2046. {
  2047. $t_posts = Database :: get_course_table(TABLE_FORUM_POST);
  2048. $t_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  2049. $t_users = Database :: get_main_table(TABLE_MAIN_USER);
  2050. $t_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2051. $t_session_rel_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2052. $is_western_name_order = api_is_western_name_order();
  2053. if ($is_western_name_order) {
  2054. $orderby = 'ORDER BY user.firstname, user.lastname ';
  2055. } else {
  2056. $orderby = 'ORDER BY user.lastname, user.firstname';
  2057. }
  2058. $course_id = api_get_course_int_id();
  2059. $sql1 = "SELECT user_id FROM $t_qualify
  2060. WHERE c_id = $course_id AND thread_id = '".$thread_id."'";
  2061. $result1 = Database::query($sql1);
  2062. $cad = '';
  2063. while ($row = Database::fetch_array($result1)) {
  2064. $cad .= $row['user_id'].',';
  2065. }
  2066. if ($cad == '') {
  2067. $cad = '0';
  2068. } else {
  2069. $cad = substr($cad, 0, strlen($cad) - 1);
  2070. }
  2071. if (api_get_session_id()) {
  2072. $session_info = api_get_session_info(api_get_session_id());
  2073. $user_to_avoid = "'".$session_info['id_coach']."', '".$session_info['session_admin_id']."'";
  2074. //not showing coaches
  2075. $sql = "SELECT DISTINCT user.id, user.lastname, user.firstname, post.thread_id
  2076. FROM $t_posts post , $t_users user, $t_session_rel_user session_rel_user_rel_course
  2077. WHERE poster_id = user.id
  2078. AND user.id NOT IN (".$cad.")
  2079. AND user.id = session_rel_user_rel_course.user_id
  2080. AND session_rel_user_rel_course.status<>'2'
  2081. AND session_rel_user_rel_course.user_id NOT IN ($user_to_avoid)
  2082. AND post.thread_id = ".intval($thread_id)."
  2083. AND session_id = ".api_get_session_id()."
  2084. AND session_rel_user_rel_course.c_id = $course_id AND post.c_id = $course_id $orderby ";
  2085. } else {
  2086. $sql = "SELECT DISTINCT user.id, user.lastname, user.firstname, post.thread_id
  2087. FROM $t_posts post, $t_users user,$t_course_user course_user
  2088. WHERE post.poster_id = user.id
  2089. AND user.id NOT IN (".$cad.")
  2090. AND user.id = course_user.user_id
  2091. AND course_user.relation_type<>".COURSE_RELATION_TYPE_RRHH."
  2092. AND post.thread_id = ".intval($thread_id)."
  2093. AND course_user.status not in('1')
  2094. AND course_user.c_id = $course_id AND post.c_id = $course_id $orderby";
  2095. }
  2096. $result = Database::query($sql);
  2097. return $result;
  2098. }
  2099. /**
  2100. * This function retrieves all the information of a given forum_id
  2101. *
  2102. * @param $forum_id integer that indicates the forum
  2103. * @return array returns
  2104. *
  2105. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2106. * @version february 2006, dokeos 1.8
  2107. *
  2108. * @deprecated this functionality is now moved to get_forums($forum_id)
  2109. */
  2110. function get_forum_information($forum_id, $courseId = 0)
  2111. {
  2112. $table_forums = Database :: get_course_table(TABLE_FORUM);
  2113. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  2114. $courseId = empty($courseId) ? api_get_course_int_id(): intval($courseId);
  2115. $forum_id = intval($forum_id);
  2116. $sql = "SELECT *
  2117. FROM $table_forums forums
  2118. INNER JOIN $table_item_property item_properties
  2119. ON (forums.c_id = item_properties.c_id)
  2120. WHERE
  2121. item_properties.tool = '".TOOL_FORUM."' AND
  2122. item_properties.ref = '".$forum_id."' AND
  2123. forums.forum_id = '".$forum_id."' AND
  2124. forums.c_id = ".$courseId."
  2125. ";
  2126. $result = Database::query($sql);
  2127. $row = Database::fetch_array($result, 'ASSOC');
  2128. $row['approval_direct_post'] = 0;
  2129. // We can't anymore change this option, so it should always be activated.
  2130. return $row;
  2131. }
  2132. /**
  2133. * This function retrieves all the information of a given forumcategory id
  2134. *
  2135. * @param $cat_id integer that indicates the forum
  2136. *
  2137. * @return array returns if there are category or bool returns if there aren't category
  2138. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2139. * @version february 2006, dokeos 1.8
  2140. */
  2141. function get_forumcategory_information($cat_id)
  2142. {
  2143. $table_categories = Database :: get_course_table(TABLE_FORUM_CATEGORY);
  2144. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  2145. $course_id = api_get_course_int_id();
  2146. $sql = "SELECT *
  2147. FROM ".$table_categories." forumcategories, ".$table_item_property." item_properties
  2148. WHERE
  2149. forumcategories.c_id = $course_id AND
  2150. item_properties.c_id = $course_id AND
  2151. item_properties.tool='".TOOL_FORUM_CATEGORY."' AND
  2152. item_properties.ref='".Database::escape_string($cat_id)."' AND
  2153. forumcategories.cat_id='".Database::escape_string($cat_id)."'";
  2154. $result = Database::query($sql);
  2155. $row = Database::fetch_array($result);
  2156. return $row;
  2157. }
  2158. /**
  2159. * This function counts the number of forums inside a given category
  2160. *
  2161. * @param int $cat_id the id of the forum category
  2162. * @todo an additional parameter that takes the visibility into account. For instance $countinvisible=0 would return the number
  2163. * of visible forums, $countinvisible=1 would return the number of visible and invisible forums
  2164. * @return int the number of forums inside the given category
  2165. *
  2166. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2167. * @version february 2006, dokeos 1.8
  2168. */
  2169. function count_number_of_forums_in_category($cat_id)
  2170. {
  2171. $table_forums = Database :: get_course_table(TABLE_FORUM);
  2172. $course_id = api_get_course_int_id();
  2173. $sql = "SELECT count(*) AS number_of_forums
  2174. FROM ".$table_forums."
  2175. WHERE c_id = $course_id AND forum_category='".Database::escape_string($cat_id)."'";
  2176. $result = Database::query($sql);
  2177. $row = Database::fetch_array($result);
  2178. return $row['number_of_forums'];
  2179. }
  2180. /**
  2181. * This function update a thread
  2182. *
  2183. * @param array $values - The form Values
  2184. * @return void HTML
  2185. *
  2186. */
  2187. function updateThread($values)
  2188. {
  2189. $threadTable = Database :: get_course_table(TABLE_FORUM_THREAD);
  2190. $courseId = api_get_course_int_id();
  2191. $params = [
  2192. 'thread_title' => $values['thread_title'],
  2193. 'thread_sticky' => isset($values['thread_sticky']) ? $values['thread_sticky'] : null,
  2194. 'thread_title_qualify' => $values['calification_notebook_title'],
  2195. 'thread_qualify_max' => api_float_val($values['numeric_calification']),
  2196. 'thread_weight' => api_float_val($values['weight_calification']),
  2197. 'thread_peer_qualify' => $values['thread_peer_qualify'],
  2198. ];
  2199. $where = ['c_id = ? AND thread_id = ?' => [$courseId, $values['thread_id']]];
  2200. Database::update($threadTable, $params, $where);
  2201. if (api_is_course_admin() == true) {
  2202. $option_chek = isset($values['thread_qualify_gradebook']) ? $values['thread_qualify_gradebook'] : false; // values 1 or 0
  2203. if ($option_chek) {
  2204. $id = $values['thread_id'];
  2205. $titleGradebook = Security::remove_XSS(stripslashes($values['calification_notebook_title']));
  2206. $valueCalification = isset($values['numeric_calification']) ? intval($values['numeric_calification']) : 0;
  2207. $weightCalification = isset($values['weight_calification']) ? floatval($values['weight_calification']) : 0;
  2208. $description = '';
  2209. $sessionId = api_get_session_id();
  2210. $courseId = api_get_course_id();
  2211. $linkInfo = GradebookUtils::isResourceInCourseGradebook(
  2212. $courseId,
  2213. LINK_FORUM_THREAD,
  2214. $id,
  2215. $sessionId
  2216. );
  2217. $linkId = $linkInfo['id'];
  2218. if (!$linkInfo) {
  2219. GradebookUtils::add_resource_to_course_gradebook(
  2220. $values['category_id'],
  2221. $courseId,
  2222. LINK_FORUM_THREAD,
  2223. $id,
  2224. $titleGradebook,
  2225. $weightCalification,
  2226. $valueCalification,
  2227. $description,
  2228. 1,
  2229. $sessionId
  2230. );
  2231. } else {
  2232. $em = Database::getManager();
  2233. $gradebookLink = $em->getRepository('ChamiloCoreBundle:GradebookLink')->find($linkId);
  2234. $gradebookLink->setWeight($weightCalification);
  2235. $em->persist($gradebookLink);
  2236. $em->flush();
  2237. }
  2238. }
  2239. }
  2240. $message = get_lang('EditPostStored').'<br />';
  2241. Display::addFlash(Display::return_message($message, 'confirmation', false));
  2242. }
  2243. /**
  2244. * This function stores a new thread. This is done through an entry in the forum_thread table AND
  2245. * in the forum_post table because. The threads are also stored in the item_property table. (forum posts are not (yet))
  2246. *
  2247. * @param array $current_forum
  2248. * @param array $values
  2249. * @param array $courseInfo
  2250. * @param bool $showMessage
  2251. * @param int $userId Optional. The user ID
  2252. * @param int $sessionId
  2253. * @return int
  2254. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2255. * @version february 2006, dokeos 1.8
  2256. */
  2257. function store_thread($current_forum, $values, $courseInfo = array(), $showMessage = true, $userId = 0, $sessionId = 0)
  2258. {
  2259. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2260. $userId = $userId ?: api_get_user_id();
  2261. $course_id = $courseInfo['real_id'];
  2262. $courseCode = $courseInfo['code'];
  2263. $groupId = api_get_group_id();
  2264. $groupInfo = GroupManager::get_group_properties($groupId);
  2265. $groupIid = null;
  2266. if (!empty($groupInfo)) {
  2267. $groupIid = $groupInfo['iid'];
  2268. }
  2269. $sessionId = $sessionId ?: api_get_session_id();
  2270. $em = Database::getManager();
  2271. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  2272. $gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
  2273. $upload_ok = 1;
  2274. $has_attachment = false;
  2275. if (!empty($_FILES['user_upload']['name'])) {
  2276. $upload_ok = process_uploaded_file($_FILES['user_upload']);
  2277. $has_attachment = true;
  2278. }
  2279. if (!$upload_ok) {
  2280. if ($showMessage) {
  2281. Display::addFlash(
  2282. Display::return_message(get_lang('UplNoFileUploaded'), 'error', false)
  2283. );
  2284. }
  2285. return null;
  2286. }
  2287. $post_date = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  2288. if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
  2289. $visible = 0; // The post has not been approved yet.
  2290. } else {
  2291. $visible = 1;
  2292. }
  2293. $clean_post_title = $values['post_title'];
  2294. // We first store an entry in the forum_thread table because the thread_id is used in the forum_post table.
  2295. $lastThread = new CForumThread();
  2296. $lastThread
  2297. ->setCId($course_id)
  2298. ->setThreadTitle($clean_post_title)
  2299. ->setForumId($values['forum_id'])
  2300. ->setThreadPosterId($userId)
  2301. ->setThreadPosterName(isset($values['poster_name']) ? $values['poster_name'] : null)
  2302. ->setThreadDate($post_date)
  2303. ->setThreadSticky(isset($values['thread_sticky']) ? $values['thread_sticky'] : 0)
  2304. ->setThreadTitleQualify(
  2305. isset($values['calification_notebook_title']) ? $values['calification_notebook_title'] : null
  2306. )
  2307. ->setThreadQualifyMax(isset($values['numeric_calification']) ? (int) $values['numeric_calification'] : 0)
  2308. ->setThreadWeight(isset($values['weight_calification']) ? (int) $values['weight_calification'] : 0)
  2309. ->setThreadPeerQualify(isset($values['thread_peer_qualify']) ? (int) $values['thread_peer_qualify'] : 0)
  2310. ->setSessionId($sessionId)
  2311. ->setLpItemId(isset($values['lp_item_id']) ? (int) $values['lp_item_id'] : 0)
  2312. ->setThreadId(0)
  2313. ->setLocked(0)
  2314. ;
  2315. $em->persist($lastThread);
  2316. $em->flush();
  2317. // Add option gradebook qualify.
  2318. if (isset($values['thread_qualify_gradebook']) &&
  2319. 1 == $values['thread_qualify_gradebook']
  2320. ) {
  2321. // Add function gradebook.
  2322. $resourcetype = 5;
  2323. $resourceid = $lastThread->getIid();
  2324. $resourcename = stripslashes($values['calification_notebook_title']);
  2325. $maxqualify = $values['numeric_calification'];
  2326. $weigthqualify = $values['weight_calification'];
  2327. $resourcedescription = '';
  2328. GradebookUtils::add_resource_to_course_gradebook(
  2329. $values['category_id'],
  2330. $courseCode,
  2331. $resourcetype,
  2332. $resourceid,
  2333. $resourcename,
  2334. $weigthqualify,
  2335. $maxqualify,
  2336. $resourcedescription,
  2337. 0,
  2338. $sessionId
  2339. );
  2340. }
  2341. if ($lastThread->getIid()) {
  2342. $lastThread->setThreadId($lastThread->getIid());
  2343. $em->merge($lastThread);
  2344. $em->flush();
  2345. api_item_property_update(
  2346. $courseInfo,
  2347. TOOL_FORUM_THREAD,
  2348. $lastThread->getIid(),
  2349. 'ForumThreadAdded',
  2350. $userId,
  2351. $groupIid,
  2352. null,
  2353. null,
  2354. null,
  2355. $sessionId
  2356. );
  2357. // If the forum properties tell that the posts have to be approved
  2358. // we have to put the whole thread invisible,
  2359. // because otherwise the students will see the thread and not the post
  2360. // in the thread.
  2361. // We also have to change $visible because the post itself has to be
  2362. // visible in this case (otherwise the teacher would have
  2363. // to make the thread visible AND the post.
  2364. // Default behaviour
  2365. api_set_default_visibility(
  2366. $lastThread->getIid(),
  2367. TOOL_FORUM_THREAD,
  2368. $groupIid,
  2369. $courseInfo,
  2370. $sessionId,
  2371. $userId
  2372. );
  2373. if ($visible == 0) {
  2374. api_item_property_update(
  2375. $courseInfo,
  2376. TOOL_FORUM_THREAD,
  2377. $lastThread->getIid(),
  2378. 'invisible',
  2379. $userId,
  2380. $groupIid
  2381. );
  2382. $visible = 1;
  2383. }
  2384. }
  2385. // We now store the content in the table_post table.
  2386. $lastPost = new CForumPost();
  2387. $lastPost
  2388. ->setCId($course_id)
  2389. ->setPostTitle($clean_post_title)
  2390. ->setPostText($values['post_text'])
  2391. ->setThreadId($lastThread->getIid())
  2392. ->setForumId($values['forum_id'])
  2393. ->setPosterId($userId)
  2394. ->setPosterName(isset($values['poster_name']) ? $values['poster_name'] : null)
  2395. ->setPostDate($post_date)
  2396. ->setPostNotification(isset($values['post_notification']) ? (int) $values['post_notification'] : null)
  2397. ->setPostParentId(null)
  2398. ->setVisible($visible)
  2399. ->setPostId(0)
  2400. ->setStatus(CForumPost::STATUS_VALIDATED);
  2401. if ($current_forum['moderated']) {
  2402. $lastPost->setStatus(
  2403. api_is_course_admin() ? CForumPost::STATUS_VALIDATED : CForumPost::STATUS_WAITING_MODERATION
  2404. );
  2405. }
  2406. $em->persist($lastPost);
  2407. $em->flush();
  2408. $last_post_id = $lastPost->getIid();
  2409. if ($last_post_id) {
  2410. $lastPost->setPostId($last_post_id);
  2411. $em->merge($lastPost);
  2412. $em->flush();
  2413. }
  2414. // Update attached files
  2415. if (!empty($_POST['file_ids']) && is_array($_POST['file_ids'])) {
  2416. foreach ($_POST['file_ids'] as $key => $id) {
  2417. editAttachedFile(
  2418. array(
  2419. 'comment' => $_POST['file_comments'][$key],
  2420. 'post_id' => $last_post_id
  2421. ),
  2422. $id
  2423. );
  2424. }
  2425. }
  2426. // Now we have to update the thread table to fill the thread_last_post
  2427. // field (so that we know when the thread has been updated for the last time).
  2428. $sql = "UPDATE $table_threads
  2429. SET thread_last_post = '".Database::escape_string($last_post_id)."'
  2430. WHERE
  2431. c_id = $course_id AND
  2432. thread_id='".Database::escape_string($lastThread->getIid())."'";
  2433. $result = Database::query($sql);
  2434. $message = get_lang('NewThreadStored');
  2435. // Storing the attachments if any.
  2436. if ($has_attachment) {
  2437. // Try to add an extension to the file if it hasn't one.
  2438. $new_file_name = add_ext_on_mime(
  2439. stripslashes($_FILES['user_upload']['name']),
  2440. $_FILES['user_upload']['type']
  2441. );
  2442. if (!filter_extension($new_file_name)) {
  2443. if ($showMessage) {
  2444. Display::addFlash(Display::return_message(
  2445. get_lang('UplUnableToSaveFileFilteredExtension'),
  2446. 'error'
  2447. ));
  2448. }
  2449. } else {
  2450. if ($result) {
  2451. add_forum_attachment_file(
  2452. isset($values['file_comment']) ? $values['file_comment'] : null,
  2453. $last_post_id
  2454. );
  2455. }
  2456. }
  2457. } else {
  2458. $message .= '<br />';
  2459. }
  2460. if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
  2461. $message .= get_lang('MessageHasToBeApproved').'<br />';
  2462. $message .= get_lang('ReturnTo').' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
  2463. get_lang('Forum').'</a><br />';
  2464. } else {
  2465. $message .= get_lang('ReturnTo').' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
  2466. get_lang('Forum').'</a><br />';
  2467. $message .= get_lang('ReturnTo').' <a href="viewthread.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'&gradebook='.$gradebook.'&thread='.$lastThread->getIid().'">'.
  2468. get_lang('Message').'</a>';
  2469. }
  2470. $reply_info['new_post_id'] = $last_post_id;
  2471. $my_post_notification = isset($values['post_notification']) ? $values['post_notification'] : null;
  2472. if ($my_post_notification == 1) {
  2473. set_notification('thread', $lastThread->getIid(), true);
  2474. }
  2475. send_notification_mails(
  2476. $current_forum['forum_id'],
  2477. $lastThread->getIid(),
  2478. $reply_info,
  2479. $courseInfo['code']
  2480. );
  2481. Session::erase('formelements');
  2482. Session::erase('origin');
  2483. Session::erase('breadcrumbs');
  2484. Session::erase('addedresource');
  2485. Session::erase('addedresourceid');
  2486. if ($showMessage) {
  2487. Display::addFlash(Display::return_message($message, 'success', false));
  2488. }
  2489. return $lastThread->getIid();
  2490. }
  2491. /**
  2492. * This function displays the form that is used to UPDATE a Thread.
  2493. * @param array $currentForum
  2494. * @param array $forumSetting
  2495. * @param array $formValues
  2496. * @return void HMTL
  2497. * @author José Loguercio <jose.loguercio@beeznest.com>
  2498. * @version february 2016, chamilo 1.10.4
  2499. */
  2500. function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
  2501. {
  2502. $myThread = isset($_GET['thread']) ? intval($_GET['thread']) : '';
  2503. $myForum = isset($_GET['forum']) ? intval($_GET['forum']) : '';
  2504. $myGradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
  2505. $form = new FormValidator(
  2506. 'thread',
  2507. 'post',
  2508. api_get_self() . '?' . http_build_query([
  2509. 'forum' => $myForum,
  2510. 'gradebook' => $myGradebook,
  2511. 'thread' => $myThread,
  2512. ]) . '&' . api_get_cidreq()
  2513. );
  2514. $form->addElement('header', get_lang('EditThread'));
  2515. $form->setConstants(array('forum' => '5'));
  2516. $form->addElement('hidden', 'forum_id', $myForum);
  2517. $form->addElement('hidden', 'thread_id', $myThread);
  2518. $form->addElement('hidden', 'gradebook', $myGradebook);
  2519. $form->addElement('text', 'thread_title', get_lang('Title'));
  2520. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  2521. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  2522. if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && ($myThread)) {
  2523. // Thread qualify
  2524. if (Gradebook::is_active()) {
  2525. //Loading gradebook select
  2526. GradebookUtils::load_gradebook_select_in_tool($form);
  2527. $form->addElement(
  2528. 'checkbox',
  2529. 'thread_qualify_gradebook',
  2530. '',
  2531. get_lang('QualifyThreadGradebook'),
  2532. [
  2533. 'id' => 'thread_qualify_gradebook'
  2534. ]
  2535. );
  2536. } else {
  2537. $form->addElement('hidden', 'thread_qualify_gradebook', false);
  2538. }
  2539. $form->addElement('html', '<div id="options_field" style="display:none">');
  2540. $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric'));
  2541. $form->applyFilter('numeric_calification', 'html_filter');
  2542. $form->addElement('text', 'calification_notebook_title', get_lang('TitleColumnGradebook'));
  2543. $form->applyFilter('calification_notebook_title', 'html_filter');
  2544. $form->addElement(
  2545. 'text',
  2546. 'weight_calification',
  2547. get_lang('QualifyWeight'),
  2548. array('value' => '0.00', 'onfocus' => "javascript: this.select();")
  2549. );
  2550. $form->applyFilter('weight_calification', 'html_filter');
  2551. $group = array();
  2552. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1);
  2553. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0);
  2554. $form->addGroup(
  2555. $group,
  2556. '',
  2557. [
  2558. get_lang('ForumThreadPeerScoring'),
  2559. get_lang('ForumThreadPeerScoringComment'),
  2560. ]
  2561. );
  2562. $form->addElement('html', '</div>');
  2563. }
  2564. if ($forumSetting['allow_sticky'] && api_is_allowed_to_edit(null, true)) {
  2565. $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost'));
  2566. }
  2567. $form->addElement('html', '</div>');
  2568. if (!empty($formValues)) {
  2569. $defaults['thread_qualify_gradebook'] = ($formValues['threadQualifyMax'] > 0 && empty($_POST)) ? 1 : 0 ;
  2570. $defaults['thread_title'] = prepare4display($formValues['threadTitle']);
  2571. $defaults['thread_sticky'] = strval(intval($formValues['threadSticky']));
  2572. $defaults['thread_peer_qualify'] = intval($formValues['threadPeerQualify']);
  2573. $defaults['numeric_calification'] = $formValues['threadQualifyMax'];
  2574. $defaults['calification_notebook_title'] = $formValues['threadTitleQualify'];
  2575. $defaults['weight_calification'] = $formValues['threadWeight'];
  2576. } else {
  2577. $defaults['thread_qualify_gradebook'] = 0;
  2578. $defaults['numeric_calification'] = 0;
  2579. $defaults['calification_notebook_title'] = '';
  2580. $defaults['weight_calification'] = 0;
  2581. $defaults['thread_peer_qualify'] = 0;
  2582. }
  2583. $form->setDefaults(isset($defaults) ? $defaults : null);
  2584. $form->addButtonUpdate(get_lang('ModifyThread'), 'SubmitPost');
  2585. if ($form->validate()) {
  2586. $check = Security::check_token('post');
  2587. if ($check) {
  2588. $values = $form->exportValues();
  2589. if (isset($values['thread_qualify_gradebook']) &&
  2590. $values['thread_qualify_gradebook'] == '1' &&
  2591. empty($values['weight_calification'])
  2592. ) {
  2593. Display::addFlash(Display::return_message(
  2594. get_lang('YouMustAssignWeightOfQualification').'&nbsp;<a href="javascript:window.history.go(-1);">'.
  2595. get_lang('Back').'</a>',
  2596. 'error',
  2597. false
  2598. ));
  2599. return false;
  2600. }
  2601. Security::clear_token();
  2602. return $values;
  2603. }
  2604. } else {
  2605. $token = Security::get_token();
  2606. $form->addElement('hidden', 'sec_token');
  2607. $form->setConstants(array('sec_token' => $token));
  2608. $form->display();
  2609. }
  2610. }
  2611. /**
  2612. * This function displays the form that is used to add a post. This can be a new thread or a reply.
  2613. * @param array $current_forum
  2614. * @param array $forum_setting
  2615. * @param string $action is the parameter that determines if we are
  2616. * 1. newthread: adding a new thread (both empty) => No I-frame
  2617. * 2. replythread: Replying to a thread ($action = replythread) => I-frame with the complete thread (if enabled)
  2618. * 3. replymessage: Replying to a message ($action =replymessage) => I-frame with the complete thread (if enabled) (I first thought to put and I-frame with the message only)
  2619. * 4. quote: Quoting a message ($action= quotemessage) => I-frame with the complete thread (if enabled). The message will be in the reply. (I first thought not to put an I-frame here)
  2620. * @return FormValidator
  2621. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2622. * @version february 2006, dokeos 1.8
  2623. */
  2624. function show_add_post_form($current_forum, $forum_setting, $action, $id = '', $form_values = '')
  2625. {
  2626. $_user = api_get_user_info();
  2627. $action = isset($action) ? Security::remove_XSS($action) : '';
  2628. $myThread = isset($_GET['thread']) ? (int) $_GET['thread'] : '';
  2629. $forumId = isset($_GET['forum']) ? (int) $_GET['forum'] : '';
  2630. $my_post = isset($_GET['post']) ? (int) $_GET['post'] : '';
  2631. $my_gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
  2632. $url = api_get_self() . '?' . http_build_query([
  2633. 'action' => $action,
  2634. 'forum' => $forumId,
  2635. 'gradebook' => $my_gradebook,
  2636. 'thread' => $myThread,
  2637. 'post' => $my_post
  2638. ]) . '&' . api_get_cidreq();
  2639. $form = new FormValidator(
  2640. 'thread',
  2641. 'post',
  2642. $url
  2643. );
  2644. $form->setConstants(array('forum' => '5'));
  2645. // Setting the form elements.
  2646. $form->addElement('hidden', 'forum_id', $forumId);
  2647. $form->addElement('hidden', 'thread_id', $myThread);
  2648. $form->addElement('hidden', 'gradebook', $my_gradebook);
  2649. $form->addElement('hidden', 'action', $action);
  2650. // If anonymous posts are allowed we also display a form to allow the user to put his name or username in.
  2651. if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) {
  2652. $form->addElement('text', 'poster_name', get_lang('Name'));
  2653. $form->applyFilter('poster_name', 'html_filter');
  2654. }
  2655. $form->addElement('text', 'post_title', get_lang('Title'));
  2656. $form->addHtmlEditor(
  2657. 'post_text',
  2658. get_lang('Text'),
  2659. true,
  2660. false,
  2661. api_is_allowed_to_edit(null, true) ? array(
  2662. 'ToolbarSet' => 'Forum',
  2663. 'Width' => '100%',
  2664. 'Height' => '300',
  2665. ) : array(
  2666. 'ToolbarSet' => 'ForumStudent',
  2667. 'Width' => '100%',
  2668. 'Height' => '300',
  2669. 'UserStatus' => 'student'
  2670. )
  2671. );
  2672. $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required');
  2673. $iframe = null;
  2674. $myThread = Security::remove_XSS($myThread);
  2675. if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread' && !empty($myThread)) {
  2676. $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?".api_get_cidreq()."&forum=".intval($forumId)."&thread=".$myThread."#".Security::remove_XSS($my_post)."\" width=\"100%\"></iframe>";
  2677. }
  2678. if (!empty($iframe)) {
  2679. $form->addElement('label', get_lang('Thread'), $iframe);
  2680. }
  2681. if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && !($myThread)) {
  2682. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  2683. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  2684. // Thread qualify
  2685. if (Gradebook::is_active()) {
  2686. //Loading gradebook select
  2687. GradebookUtils::load_gradebook_select_in_tool($form);
  2688. $form->addElement(
  2689. 'checkbox',
  2690. 'thread_qualify_gradebook',
  2691. '',
  2692. get_lang('QualifyThreadGradebook'),
  2693. 'onclick="javascript:if(this.checked==true){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"'
  2694. );
  2695. } else {
  2696. $form->addElement('hidden', 'thread_qualify_gradebook', false);
  2697. }
  2698. $form->addElement('html', '<div id="options_field" style="display:none">');
  2699. $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric'));
  2700. $form->applyFilter('numeric_calification', 'html_filter');
  2701. $form->addElement('text', 'calification_notebook_title', get_lang('TitleColumnGradebook'));
  2702. $form->applyFilter('calification_notebook_title', 'html_filter');
  2703. $form->addElement(
  2704. 'text',
  2705. 'weight_calification',
  2706. get_lang('QualifyWeight'),
  2707. array('value' => '0.00', 'onfocus' => "javascript: this.select();")
  2708. );
  2709. $form->applyFilter('weight_calification', 'html_filter');
  2710. $group = array();
  2711. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1);
  2712. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0);
  2713. $form->addGroup(
  2714. $group,
  2715. '',
  2716. [
  2717. get_lang('ForumThreadPeerScoring'),
  2718. get_lang('ForumThreadPeerScoringComment'),
  2719. ]
  2720. );
  2721. $form->addElement('html', '</div>');
  2722. $form->addElement('html', '</div>');
  2723. }
  2724. if ($forum_setting['allow_sticky'] && api_is_allowed_to_edit(null, true) && $action == 'newthread') {
  2725. $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost'));
  2726. }
  2727. if (in_array($action, ['quote', 'replymessage'])) {
  2728. $form->addFile('user_upload[]', get_lang('Attachment'));
  2729. $form->addButton(
  2730. 'add_attachment',
  2731. get_lang('AddAttachment'),
  2732. 'paperclip',
  2733. 'default',
  2734. 'default',
  2735. null,
  2736. ['id' => 'reply-add-attachment']
  2737. );
  2738. } else {
  2739. $form->addFile('user_upload', get_lang('Attachment'));
  2740. }
  2741. // Setting the class and text of the form title and submit button.
  2742. if ($action == 'quote') {
  2743. $form->addButtonCreate(get_lang('QuoteMessage'), 'SubmitPost');
  2744. } elseif ($action == 'replythread') {
  2745. $form->addButtonCreate(get_lang('ReplyToThread'), 'SubmitPost');
  2746. } elseif ($action == 'replymessage') {
  2747. $form->addButtonCreate(get_lang('ReplyToMessage'), 'SubmitPost');
  2748. } else {
  2749. $form->addButtonCreate(get_lang('CreateThread'), 'SubmitPost');
  2750. }
  2751. if (!empty($form_values)) {
  2752. $defaults['post_title'] = prepare4display($form_values['post_title']);
  2753. $defaults['post_text'] = prepare4display($form_values['post_text']);
  2754. $defaults['post_notification'] = strval(intval($form_values['post_notification']));
  2755. $defaults['thread_sticky'] = strval(intval($form_values['thread_sticky']));
  2756. $defaults['thread_peer_qualify'] = intval($form_values['thread_peer_qualify']);
  2757. } else {
  2758. $defaults['thread_peer_qualify'] = 0;
  2759. }
  2760. // If we are quoting a message we have to retrieve the information of the post we are quoting so that
  2761. // we can add this as default to the textarea.
  2762. if (($action == 'quote' || $action == 'replymessage') && isset($my_post)) {
  2763. // We also need to put the parent_id of the post in a hidden form when
  2764. // we are quoting or replying to a message (<> reply to a thread !!!)
  2765. $form->addHidden('post_parent_id', intval($my_post));
  2766. // If we are replying or are quoting then we display a default title.
  2767. $values = get_post_information($my_post);
  2768. $posterInfo = api_get_user_info($values['poster_id']);
  2769. $posterName = '';
  2770. if ($posterInfo) {
  2771. $posterName = $posterInfo['complete_name'];
  2772. }
  2773. $defaults['post_title'] = get_lang('ReplyShort').api_html_entity_decode($values['post_title'], ENT_QUOTES);
  2774. // When we are quoting a message then we have to put that message into the wysiwyg editor.
  2775. // Note: The style has to be hardcoded here because using class="quote" didn't work.
  2776. if ($action == 'quote') {
  2777. $defaults['post_text'] = '<div>&nbsp;</div>
  2778. <div style="margin: 5px;">
  2779. <div style="font-size: 90%; font-style: italic;">'.
  2780. get_lang('Quoting').' '.$posterName.':</div>
  2781. <div style="color: #006600; font-size: 90%; font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">'.
  2782. prepare4display($values['post_text']).'
  2783. </div>
  2784. </div>
  2785. <div>&nbsp;</div>
  2786. <div>&nbsp;</div>
  2787. ';
  2788. }
  2789. }
  2790. $form->setDefaults(isset($defaults) ? $defaults : []);
  2791. // The course admin can make a thread sticky (=appears with special icon and always on top).
  2792. $form->addRule('post_title', get_lang('ThisFieldIsRequired'), 'required');
  2793. if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) {
  2794. $form->addRule('poster_name', get_lang('ThisFieldIsRequired'), 'required');
  2795. }
  2796. // Validation or display
  2797. if ($form->validate()) {
  2798. $check = Security::check_token('post');
  2799. if ($check) {
  2800. $values = $form->exportValues();
  2801. if (isset($values['thread_qualify_gradebook']) &&
  2802. $values['thread_qualify_gradebook'] == '1' &&
  2803. empty($values['weight_calification'])
  2804. ) {
  2805. Display::addFlash(
  2806. Display::return_message(
  2807. get_lang('YouMustAssignWeightOfQualification').'&nbsp;<a href="javascript:window.history.go(-1);">'.get_lang('Back').'</a>',
  2808. 'error',
  2809. false
  2810. )
  2811. );
  2812. return false;
  2813. }
  2814. switch ($action) {
  2815. case 'newthread':
  2816. $myThread = store_thread($current_forum, $values);
  2817. break;
  2818. case 'quote':
  2819. case 'replythread':
  2820. case 'replymessage':
  2821. store_reply($current_forum, $values);
  2822. break;
  2823. }
  2824. $url = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&'.http_build_query(
  2825. [
  2826. 'forum' => $forumId,
  2827. 'thread' => $myThread
  2828. ]
  2829. );
  2830. Security::clear_token();
  2831. header('Location: '.$url);
  2832. exit;
  2833. }
  2834. } else {
  2835. $token = Security::get_token();
  2836. $form->addElement('hidden', 'sec_token');
  2837. $form->setConstants(array('sec_token' => $token));
  2838. // Delete from $_SESSION forum attachment from other posts
  2839. // and keep only attachments for new post
  2840. clearAttachedFiles(FORUM_NEW_POST);
  2841. // Get forum attachment ajax table to add it to form
  2842. $attachmentAjaxTable = getAttachmentsAjaxTable(0, $current_forum['forum_id']);
  2843. $ajaxHtml = $attachmentAjaxTable;
  2844. $form->addElement('html', $ajaxHtml);
  2845. return $form;
  2846. }
  2847. }
  2848. /**
  2849. * @param array $threadInfo
  2850. * @param integer $user_id
  2851. * @param integer $thread_id
  2852. * @param integer $thread_qualify
  2853. * @param integer $qualify_time
  2854. * @param integer $session_id
  2855. * @return array optional
  2856. * @author Isaac Flores <isaac.flores@dokeos.com>, U.N.A.S University
  2857. * @version October 2008, dokeos 1.8.6
  2858. */
  2859. function saveThreadScore(
  2860. $threadInfo,
  2861. $user_id,
  2862. $thread_id,
  2863. $thread_qualify = 0,
  2864. $qualify_time,
  2865. $session_id = 0
  2866. ) {
  2867. $table_threads_qualify = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  2868. $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
  2869. $course_id = api_get_course_int_id();
  2870. $session_id = intval($session_id);
  2871. $currentUserId = api_get_user_id();
  2872. if ($user_id == strval(intval($user_id)) &&
  2873. $thread_id == strval(intval($thread_id)) &&
  2874. $thread_qualify == strval(floatval($thread_qualify))
  2875. ) {
  2876. // Testing
  2877. $sql = "SELECT thread_qualify_max FROM $table_threads
  2878. WHERE c_id = $course_id AND thread_id=".$thread_id;
  2879. $res_string = Database::query($sql);
  2880. $row_string = Database::fetch_array($res_string);
  2881. if ($thread_qualify <= $row_string[0]) {
  2882. if ($threadInfo['thread_peer_qualify'] == 0) {
  2883. $sql = "SELECT COUNT(*) FROM $table_threads_qualify
  2884. WHERE
  2885. c_id = $course_id AND
  2886. user_id = $user_id AND
  2887. thread_id = ".$thread_id;
  2888. } else {
  2889. $sql = "SELECT COUNT(*) FROM $table_threads_qualify
  2890. WHERE
  2891. c_id = $course_id AND
  2892. user_id = $user_id AND
  2893. qualify_user_id = $currentUserId AND
  2894. thread_id = ".$thread_id;
  2895. }
  2896. $result = Database::query($sql);
  2897. $row = Database::fetch_array($result);
  2898. if ($row[0] == 0) {
  2899. $sql = "INSERT INTO $table_threads_qualify (c_id, user_id, thread_id,qualify,qualify_user_id,qualify_time,session_id)
  2900. VALUES (".$course_id.", '".$user_id."','".$thread_id."',".(float)$thread_qualify.", '".$currentUserId."','".$qualify_time."','".$session_id."')";
  2901. Database::query($sql);
  2902. $insertId = Database::insert_id();
  2903. if ($insertId) {
  2904. $sql = "UPDATE $table_threads_qualify SET id = iid
  2905. WHERE iid = $insertId";
  2906. Database::query($sql);
  2907. }
  2908. return 'insert';
  2909. } else {
  2910. saveThreadScoreHistory(
  2911. '1',
  2912. $course_id,
  2913. $user_id,
  2914. $thread_id
  2915. );
  2916. // Update
  2917. $sql = "UPDATE $table_threads_qualify
  2918. SET
  2919. qualify = '".$thread_qualify."',
  2920. qualify_time = '".$qualify_time."'
  2921. WHERE
  2922. c_id = $course_id AND
  2923. user_id=".$user_id." AND
  2924. thread_id=".$thread_id." AND
  2925. qualify_user_id = $currentUserId
  2926. ";
  2927. Database::query($sql);
  2928. return 'update';
  2929. }
  2930. } else {
  2931. return null;
  2932. }
  2933. }
  2934. }
  2935. /**
  2936. * This function shows qualify.
  2937. * @param string $option contains the information of option to run
  2938. * @param integer $user_id contains the information the current user id
  2939. * @param integer $thread_id contains the information the current thread id
  2940. * @return integer qualify
  2941. * <code> $option=1 obtained the qualification of the current thread</code>
  2942. * @author Isaac Flores <isaac.flores@dokeos.com>, U.N.A.S University
  2943. * @version October 2008, dokeos 1.8.6
  2944. */
  2945. function showQualify($option, $user_id, $thread_id)
  2946. {
  2947. $table_threads_qualify = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  2948. $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
  2949. $course_id = api_get_course_int_id();
  2950. $user_id = intval($user_id);
  2951. $thread_id = intval($thread_id);
  2952. if (empty($user_id) || empty($thread_id)) {
  2953. return false;
  2954. }
  2955. $sql = '';
  2956. switch ($option) {
  2957. case 1:
  2958. $sql = "SELECT qualify FROM $table_threads_qualify
  2959. WHERE
  2960. c_id = $course_id AND
  2961. user_id=".$user_id." AND
  2962. thread_id=".$thread_id;
  2963. break;
  2964. case 2:
  2965. $sql = "SELECT thread_qualify_max FROM $table_threads
  2966. WHERE c_id = $course_id AND thread_id=".$thread_id;
  2967. break;
  2968. }
  2969. if (!empty($sql)) {
  2970. $rs = Database::query($sql);
  2971. $row = Database::fetch_array($rs);
  2972. return $row[0];
  2973. }
  2974. return array();
  2975. }
  2976. /**
  2977. * This function gets qualify historical.
  2978. * @param integer $user_id contains the information the current user id
  2979. * @param integer $thread_id contains the information the current thread id
  2980. * @param boolean $opt contains the information of option to run
  2981. * @return array
  2982. * @author Christian Fasanando <christian.fasanando@dokeos.com>,
  2983. * @author Isaac Flores <isaac.flores@dokeos.com>,
  2984. * @version October 2008, dokeos 1.8.6
  2985. */
  2986. function getThreadScoreHistory($user_id, $thread_id, $opt)
  2987. {
  2988. $table_threads_qualify_log = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY_LOG);
  2989. $course_id = api_get_course_int_id();
  2990. if ($opt == 'false') {
  2991. $sql = "SELECT * FROM $table_threads_qualify_log
  2992. WHERE
  2993. c_id = $course_id AND
  2994. thread_id='".Database::escape_string($thread_id)."' AND
  2995. user_id='".Database::escape_string($user_id)."'
  2996. ORDER BY qualify_time";
  2997. } else {
  2998. $sql = "SELECT * FROM $table_threads_qualify_log
  2999. WHERE
  3000. c_id = $course_id AND
  3001. thread_id='".Database::escape_string($thread_id)."' AND
  3002. user_id='".Database::escape_string($user_id)."'
  3003. ORDER BY qualify_time DESC";
  3004. }
  3005. $rs = Database::query($sql);
  3006. $log = array();
  3007. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3008. $log[] = $row;
  3009. }
  3010. return $log;
  3011. }
  3012. /**
  3013. * This function stores qualify historical.
  3014. * @param boolean contains the information of option to run
  3015. * @param string contains the information the current course id
  3016. * @param integer contains the information the current forum id
  3017. * @param integer contains the information the current user id
  3018. * @param integer contains the information the current thread id
  3019. * @param integer contains the information the current qualify
  3020. * @param string $option
  3021. * @param integer $course_id
  3022. * @param integer $user_id
  3023. * @param integer $thread_id
  3024. * @return void
  3025. * <code>$option=1 obtained the qualification of the current thread</code>
  3026. * @author Isaac Flores <isaac.flores@dokeos.com>, U.N.A.S University
  3027. * @version October 2008, dokeos 1.8.6
  3028. */
  3029. function saveThreadScoreHistory(
  3030. $option,
  3031. $course_id,
  3032. $user_id,
  3033. $thread_id
  3034. ) {
  3035. $table_threads_qualify = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  3036. $table_threads_qualify_log = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY_LOG);
  3037. $course_id = intval($course_id);
  3038. $qualify_user_id = api_get_user_id();
  3039. if ($user_id == strval(intval($user_id)) &&
  3040. $thread_id == strval(intval($thread_id)) && $option == 1
  3041. ) {
  3042. // Extract information of thread_qualify.
  3043. $sql = "SELECT qualify, qualify_time
  3044. FROM $table_threads_qualify
  3045. WHERE
  3046. c_id = $course_id AND
  3047. user_id = ".$user_id." AND
  3048. thread_id = ".$thread_id." AND
  3049. qualify_user_id = $qualify_user_id
  3050. ";
  3051. $rs = Database::query($sql);
  3052. $row = Database::fetch_array($rs);
  3053. // Insert thread_historical.
  3054. $sql = "INSERT INTO $table_threads_qualify_log (c_id, user_id, thread_id, qualify, qualify_user_id,qualify_time,session_id)
  3055. VALUES(".$course_id.", '".$user_id."','".$thread_id."',".(float) $row[0].", '".$qualify_user_id."','".$row[1]."','')";
  3056. Database::query($sql);
  3057. $insertId = Database::insert_id();
  3058. if ($insertId) {
  3059. $sql = "UPDATE $table_threads_qualify_log SET id = iid
  3060. WHERE iid = $insertId";
  3061. Database::query($sql);
  3062. }
  3063. }
  3064. }
  3065. /**
  3066. * This function shows current thread qualify .
  3067. * @param integer $threadId
  3068. * @param integer $sessionId
  3069. * @param integer $userId
  3070. *
  3071. * @return array or null if is empty
  3072. * @author Isaac Flores <isaac.flores@dokeos.com>, U.N.A.S University
  3073. * @version December 2008, dokeos 1.8.6
  3074. */
  3075. function current_qualify_of_thread($threadId, $sessionId, $userId)
  3076. {
  3077. $table_threads_qualify = Database::get_course_table(TABLE_FORUM_THREAD_QUALIFY);
  3078. $course_id = api_get_course_int_id();
  3079. $currentUserId = api_get_user_id();
  3080. $sessionId = intval($sessionId);
  3081. $threadId = intval($threadId);
  3082. $sql = "SELECT qualify FROM $table_threads_qualify
  3083. WHERE
  3084. c_id = $course_id AND
  3085. thread_id = $threadId AND
  3086. session_id = $sessionId AND
  3087. qualify_user_id = $currentUserId AND
  3088. user_id = $userId
  3089. ";
  3090. $res = Database::query($sql);
  3091. $row = Database::fetch_array($res, 'ASSOC');
  3092. return $row['qualify'];
  3093. }
  3094. /**
  3095. * This function stores a reply in the forum_post table.
  3096. * It also updates the forum_threads table (thread_replies +1 , thread_last_post, thread_date)
  3097. * @param array $current_forum
  3098. * @param array $values
  3099. * @param int $courseId Optional
  3100. * @param int $userId Optional
  3101. * @return array
  3102. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3103. * @version february 2006, dokeos 1.8
  3104. */
  3105. function store_reply($current_forum, $values, $courseId = 0, $userId = 0)
  3106. {
  3107. $courseId = !empty($courseId) ? $courseId : api_get_course_int_id();
  3108. $_course = api_get_course_info_by_id($courseId);
  3109. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3110. $post_date = api_get_utc_datetime();
  3111. $userId = $userId ?: api_get_user_id();
  3112. if ($current_forum['approval_direct_post'] == '1' &&
  3113. !api_is_allowed_to_edit(null, true)
  3114. ) {
  3115. $visible = 0;
  3116. } else {
  3117. $visible = 1;
  3118. }
  3119. $upload_ok = 1;
  3120. $return = array();
  3121. if ($upload_ok) {
  3122. // We first store an entry in the forum_post table.
  3123. $new_post_id = Database::insert(
  3124. $table_posts,
  3125. [
  3126. 'c_id' => $courseId,
  3127. 'post_title' => $values['post_title'],
  3128. 'post_text' => isset($values['post_text']) ? ($values['post_text']) : null,
  3129. 'thread_id' => $values['thread_id'],
  3130. 'forum_id' => $values['forum_id'],
  3131. 'poster_id' => $userId,
  3132. 'post_id' => 0,
  3133. 'post_date' => $post_date,
  3134. 'post_notification' => isset($values['post_notification']) ? $values['post_notification'] : null,
  3135. 'post_parent_id' => isset($values['post_parent_id']) ? $values['post_parent_id'] : null,
  3136. 'visible' => $visible,
  3137. ]
  3138. );
  3139. if ($new_post_id) {
  3140. $sql = "UPDATE $table_posts SET post_id = iid WHERE iid = $new_post_id";
  3141. Database::query($sql);
  3142. $values['new_post_id'] = $new_post_id;
  3143. $message = get_lang('ReplyAdded');
  3144. if (!empty($_POST['file_ids']) && is_array($_POST['file_ids'])) {
  3145. foreach ($_POST['file_ids'] as $key => $id) {
  3146. editAttachedFile(
  3147. array(
  3148. 'comment' => $_POST['file_comments'][$key],
  3149. 'post_id' => $new_post_id,
  3150. ),
  3151. $id
  3152. );
  3153. }
  3154. }
  3155. // Update the thread.
  3156. updateThreadInfo($values['thread_id'], $new_post_id, $post_date);
  3157. // Update the forum.
  3158. api_item_property_update(
  3159. $_course,
  3160. TOOL_FORUM,
  3161. $values['forum_id'],
  3162. 'NewMessageInForum',
  3163. $userId
  3164. );
  3165. // Insert post
  3166. api_item_property_update(
  3167. $_course,
  3168. TOOL_FORUM_POST,
  3169. $new_post_id,
  3170. 'NewPost',
  3171. $userId
  3172. );
  3173. if ($current_forum['approval_direct_post'] == '1' &&
  3174. !api_is_allowed_to_edit(null, true)
  3175. ) {
  3176. $message .= '<br />'.get_lang('MessageHasToBeApproved').'<br />';
  3177. }
  3178. if ($current_forum['moderated'] &&
  3179. !api_is_allowed_to_edit(null, true)
  3180. ) {
  3181. $message .= '<br />'.get_lang('MessageHasToBeApproved').'<br />';
  3182. }
  3183. // Setting the notification correctly.
  3184. $my_post_notification = isset($values['post_notification']) ? $values['post_notification'] : null;
  3185. if ($my_post_notification == 1) {
  3186. set_notification('thread', $values['thread_id'], true);
  3187. }
  3188. send_notification_mails(
  3189. $values['forum_id'],
  3190. $values['thread_id'],
  3191. $values
  3192. );
  3193. add_forum_attachment_file('', $new_post_id);
  3194. }
  3195. Session::erase('formelements');
  3196. Session::erase('origin');
  3197. Session::erase('breadcrumbs');
  3198. Session::erase('addedresource');
  3199. Session::erase('addedresourceid');
  3200. Display::addFlash(Display::return_message($message, 'confirmation', false));
  3201. } else {
  3202. Display::addFlash(
  3203. Display::return_message(get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst'), 'error')
  3204. );
  3205. }
  3206. return $return;
  3207. }
  3208. /**
  3209. * This function displays the form that is used to edit a post. This can be a new thread or a reply.
  3210. * @param array contains all the information about the current post
  3211. * @param array contains all the information about the current thread
  3212. * @param array contains all info about the current forum (to check if attachments are allowed)
  3213. * @param array contains the default values to fill the form
  3214. * @return void
  3215. *
  3216. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3217. * @version february 2006, dokeos 1.8
  3218. */
  3219. function show_edit_post_form(
  3220. $forum_setting,
  3221. $current_post,
  3222. $current_thread,
  3223. $current_forum,
  3224. $form_values = '',
  3225. $id_attach = 0
  3226. ) {
  3227. // Initialize the object.
  3228. $form = new FormValidator(
  3229. 'edit_post',
  3230. 'post',
  3231. api_get_self().'?'.api_get_cidreq().'&forum='.intval($_GET['forum']).'&thread='.intval($_GET['thread']).'&post='.intval($_GET['post'])
  3232. );
  3233. $form->addElement('header', get_lang('EditPost'));
  3234. // Setting the form elements.
  3235. $form->addElement('hidden', 'post_id', $current_post['post_id']);
  3236. $form->addElement('hidden', 'thread_id', $current_thread['thread_id']);
  3237. $form->addElement('hidden', 'id_attach', $id_attach);
  3238. if (empty($current_post['post_parent_id'])) {
  3239. $form->addElement('hidden', 'is_first_post_of_thread', '1');
  3240. }
  3241. $form->addElement('text', 'post_title', get_lang('Title'));
  3242. $form->applyFilter('post_title', 'html_filter');
  3243. $form->addElement(
  3244. 'html_editor',
  3245. 'post_text',
  3246. get_lang('Text'),
  3247. null,
  3248. api_is_allowed_to_edit(null, true) ? array(
  3249. 'ToolbarSet' => 'Forum',
  3250. 'Width' => '100%',
  3251. 'Height' => '400',
  3252. ) : array(
  3253. 'ToolbarSet' => 'ForumStudent',
  3254. 'Width' => '100%',
  3255. 'Height' => '400',
  3256. 'UserStatus' => 'student',
  3257. )
  3258. );
  3259. $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required');
  3260. $form->addButtonAdvancedSettings('advanced_params');
  3261. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  3262. if (!isset($_GET['edit'])) {
  3263. if (Gradebook::is_active()) {
  3264. $form->addElement('label', '<strong>'.get_lang('AlterQualifyThread').'</strong>');
  3265. $form->addElement('checkbox', 'thread_qualify_gradebook', '', get_lang('QualifyThreadGradebook'), 'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
  3266. $link_info = GradebookUtils::isResourceInCourseGradebook(
  3267. api_get_course_id(),
  3268. 5,
  3269. $_GET['thread'],
  3270. api_get_session_id()
  3271. );
  3272. if (!empty($link_info)) {
  3273. $defaults['thread_qualify_gradebook'] = true;
  3274. $defaults['category_id'] = $link_info['category_id'];
  3275. } else {
  3276. $defaults['thread_qualify_gradebook'] = false;
  3277. $defaults['category_id'] = '';
  3278. }
  3279. } else {
  3280. $form->addElement('hidden', 'thread_qualify_gradebook', false);
  3281. $defaults['thread_qualify_gradebook'] = false;
  3282. }
  3283. if (!empty($defaults['thread_qualify_gradebook'])) {
  3284. $form->addElement('html', '<div id="options_field" style="display:block">');
  3285. } else {
  3286. $form->addElement('html', '<div id="options_field" style="display:none">');
  3287. }
  3288. // Loading gradebook select
  3289. GradebookUtils::load_gradebook_select_in_tool($form);
  3290. $form->addElement(
  3291. 'text',
  3292. 'numeric_calification',
  3293. get_lang('QualificationNumeric'),
  3294. array(
  3295. 'value' => $current_thread['thread_qualify_max'],
  3296. 'style' => 'width:40px',
  3297. )
  3298. );
  3299. $form->applyFilter('numeric_calification', 'html_filter');
  3300. $form->addElement(
  3301. 'text',
  3302. 'calification_notebook_title',
  3303. get_lang('TitleColumnGradebook'),
  3304. array('value' => $current_thread['thread_title_qualify'])
  3305. );
  3306. $form->applyFilter('calification_notebook_title', 'html_filter');
  3307. $form->addElement(
  3308. 'text',
  3309. 'weight_calification',
  3310. array(get_lang('QualifyWeight'), null, ''),
  3311. array(
  3312. 'value' => $current_thread['thread_weight'],
  3313. 'style' => 'width:40px',
  3314. )
  3315. );
  3316. $form->applyFilter('weight_calification', 'html_filter');
  3317. $group = array();
  3318. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1);
  3319. $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0);
  3320. $form->addGroup(
  3321. $group,
  3322. '',
  3323. [
  3324. get_lang('ForumThreadPeerScoring'),
  3325. get_lang('ForumThreadPeerScoringComment'),
  3326. ]
  3327. );
  3328. $form->addElement('html', '</div>');
  3329. }
  3330. if ($current_forum['moderated']) {
  3331. $group = array();
  3332. $group[] = $form->createElement('radio', 'status', null, get_lang('Validated'), 1);
  3333. $group[] = $form->createElement('radio', 'status', null, get_lang('WaitingModeration'), 2);
  3334. $group[] = $form->createElement('radio', 'status', null, get_lang('Rejected'), 3);
  3335. $form->addGroup($group, 'status', get_lang('Status'));
  3336. }
  3337. $defaults['status']['status'] = isset($current_post['status']) && !empty($current_post['status']) ? $current_post['status'] : 2;
  3338. if ($forum_setting['allow_post_notification']) {
  3339. $form->addElement('checkbox', 'post_notification', '', get_lang('NotifyByEmail').' ('.$current_post['email'].')');
  3340. }
  3341. if ($forum_setting['allow_sticky'] &&
  3342. api_is_allowed_to_edit(null, true) &&
  3343. empty($current_post['post_parent_id'])
  3344. ) {
  3345. // The sticky checkbox only appears when it is the first post of a thread.
  3346. $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost'));
  3347. if ($current_thread['thread_sticky'] == 1) {
  3348. $defaults['thread_sticky'] = true;
  3349. }
  3350. }
  3351. $form->addElement('html', '</div>');
  3352. $form->addFile('user_upload[]', get_lang('Attachment'));
  3353. $form->addButton(
  3354. 'add_attachment',
  3355. get_lang('AddAttachment'),
  3356. 'paperclip',
  3357. 'default',
  3358. 'default',
  3359. null,
  3360. ['id' => 'reply-add-attachment']
  3361. );
  3362. $form->addButtonUpdate(get_lang('ModifyThread'), 'SubmitPost');
  3363. // Setting the default values for the form elements.
  3364. $defaults['post_title'] = $current_post['post_title'];
  3365. $defaults['post_text'] = $current_post['post_text'];
  3366. if ($current_post['post_notification'] == 1) {
  3367. $defaults['post_notification'] = true;
  3368. }
  3369. if (!empty($form_values)) {
  3370. $defaults['post_notification'] = Security::remove_XSS($form_values['post_notification']);
  3371. $defaults['thread_sticky'] = Security::remove_XSS($form_values['thread_sticky']);
  3372. }
  3373. $defaults['thread_peer_qualify'] = intval($current_thread['thread_peer_qualify']);
  3374. $form->setDefaults($defaults);
  3375. // The course admin can make a thread sticky (=appears with special icon and always on top).
  3376. $form->addRule('post_title', get_lang('ThisFieldIsRequired'), 'required');
  3377. // Validation or display
  3378. if ($form->validate()) {
  3379. $values = $form->exportValues();
  3380. if (isset($values['thread_qualify_gradebook']) && $values['thread_qualify_gradebook'] == '1' &&
  3381. empty($values['weight_calification'])
  3382. ) {
  3383. Display::addFlash(Display::return_message(get_lang('YouMustAssignWeightOfQualification').'&nbsp;<a href="javascript:window.history.go(-1);">'.get_lang('Back').'</a>', 'error', false));
  3384. return false;
  3385. }
  3386. return $values;
  3387. } else {
  3388. // Delete from $_SESSION forum attachment from other posts
  3389. clearAttachedFiles($current_post['post_id']);
  3390. // Get forum attachment ajax table to add it to form
  3391. $fileData = getAttachmentsAjaxTable($current_post['post_id'], $current_forum['forum_id']);
  3392. $form->addElement('html', $fileData);
  3393. $form->display();
  3394. }
  3395. }
  3396. /**
  3397. * This function stores the edit of a post in the forum_post table.
  3398. *
  3399. * @param array
  3400. * @return void HTML
  3401. *
  3402. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3403. * @version february 2006, dokeos 1.8
  3404. */
  3405. function store_edit_post($forumInfo, $values)
  3406. {
  3407. $threadTable = Database :: get_course_table(TABLE_FORUM_THREAD);
  3408. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3409. $gradebook = Security::remove_XSS($_GET['gradebook']);
  3410. $course_id = api_get_course_int_id();
  3411. //check if this post is the first of the thread
  3412. // First we check if the change affects the thread and if so we commit
  3413. // the changes (sticky and post_title=thread_title are relevant).
  3414. $posts = getPosts($forumInfo, $values['thread_id']);
  3415. $first_post = null;
  3416. if (!empty($posts) && count($posts) > 0 && isset($posts[0])) {
  3417. $first_post = $posts[0];
  3418. }
  3419. if (!empty($first_post) && $first_post['post_id'] == $values['post_id']) {
  3420. $params = [
  3421. 'thread_title' => $values['post_title'],
  3422. 'thread_sticky' => isset($values['thread_sticky']) ? $values['thread_sticky'] : null,
  3423. 'thread_title_qualify' => $values['calification_notebook_title'],
  3424. 'thread_qualify_max' => api_float_val($values['numeric_calification']),
  3425. 'thread_weight' => api_float_val($values['weight_calification']),
  3426. 'thread_peer_qualify' => $values['thread_peer_qualify'],
  3427. ];
  3428. $where = ['c_id = ? AND thread_id = ?' => [$course_id, $values['thread_id']]];
  3429. Database::update($threadTable, $params, $where);
  3430. }
  3431. $status = '';
  3432. if ($forumInfo['moderated']) {
  3433. $status = $values['status']['status'];
  3434. }
  3435. // Update the post_title and the post_text.
  3436. $params = [
  3437. 'status' => $status,
  3438. 'post_title' => $values['post_title'],
  3439. 'post_text' => $values['post_text'],
  3440. 'post_notification' => isset($values['post_notification']) ? $values['post_notification'] : '',
  3441. ];
  3442. $where = ['c_id = ? AND post_id = ?' => [$course_id, $values['post_id']]];
  3443. Database::update($table_posts, $params, $where);
  3444. // Update attached files
  3445. if (!empty($_POST['file_ids']) && is_array($_POST['file_ids'])) {
  3446. foreach ($_POST['file_ids'] as $key => $id) {
  3447. editAttachedFile(
  3448. array(
  3449. 'comment' => $_POST['file_comments'][$key],
  3450. 'post_id' => $values['post_id'],
  3451. ),
  3452. $id
  3453. );
  3454. }
  3455. }
  3456. if (!empty($values['remove_attach'])) {
  3457. delete_attachment($values['post_id']);
  3458. }
  3459. if (empty($values['id_attach'])) {
  3460. add_forum_attachment_file(
  3461. isset($values['file_comment']) ? $values['file_comment'] : null,
  3462. $values['post_id']
  3463. );
  3464. } else {
  3465. edit_forum_attachment_file(
  3466. isset($values['file_comment']) ? $values['file_comment'] : null,
  3467. $values['post_id'],
  3468. $values['id_attach']
  3469. );
  3470. }
  3471. $message = get_lang('EditPostStored').'<br />';
  3472. $message .= get_lang('ReturnTo').' <a href="viewforum.php?'.api_get_cidreq().'&forum='.intval($_GET['forum']).'&">'.get_lang('Forum').'</a><br />';
  3473. $message .= get_lang('ReturnTo').' <a href="viewthread.php?'.api_get_cidreq().'&forum='.intval($_GET['forum']).'&gradebook='.$gradebook.'&thread='.$values['thread_id'].'&post='.Security::remove_XSS($_GET['post']).'">'.get_lang('Message').'</a>';
  3474. Session::erase('formelements');
  3475. Session::erase('origin');
  3476. Session::erase('breadcrumbs');
  3477. Session::erase('addedresource');
  3478. Session::erase('addedresourceid');
  3479. Display :: display_confirmation_message($message, false);
  3480. }
  3481. /**
  3482. * This function displays the firstname and lastname of the user as a link to the user tool.
  3483. *
  3484. * @param string names
  3485. * @ in_title : title tootip
  3486. * @return string HTML
  3487. *
  3488. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3489. * @version february 2006, dokeos 1.8
  3490. */
  3491. function display_user_link($user_id, $name, $origin = '', $in_title = '')
  3492. {
  3493. if ($user_id != 0) {
  3494. $userInfo = api_get_user_info($user_id);
  3495. return '<a href="'.$userInfo['profile_url'].'">'.Security::remove_XSS($userInfo['complete_name']).'</a>';
  3496. } else {
  3497. return $name.' ('.get_lang('Anonymous').')';
  3498. }
  3499. }
  3500. /**
  3501. * This function displays the user image from the profile, with a link to the user's details.
  3502. * @param int User's database ID
  3503. * @param string User's name
  3504. * @param string the origin where the forum is called (example : learnpath)
  3505. * @return string An HTML with the anchor and the image of the user
  3506. * @author Julio Montoya <gugli100@gmail.com>
  3507. */
  3508. function display_user_image($user_id, $name, $origin = '')
  3509. {
  3510. $userInfo = api_get_user_info($user_id);
  3511. $link = '<a href="'.(!empty($origin) ? '#' : $userInfo['profile_url']).'" '.(!empty($origin) ? 'target="_self"' : '').'>';
  3512. if ($user_id != 0) {
  3513. return $link.'<img src="'.$userInfo['avatar'].'" alt="'.$name.'" title="'.$name.'" /></a>';
  3514. } else {
  3515. return $link.Display::return_icon('unknown.jpg', $name).'</a>';
  3516. }
  3517. }
  3518. /**
  3519. * The thread view counter gets increased every time someone looks at the thread
  3520. *
  3521. * @param int
  3522. * @return void
  3523. *
  3524. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3525. * @version february 2006, dokeos 1.8
  3526. */
  3527. function increase_thread_view($thread_id)
  3528. {
  3529. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  3530. $course_id = api_get_course_int_id();
  3531. $sql = "UPDATE $table_threads SET thread_views=thread_views+1
  3532. WHERE
  3533. c_id = $course_id AND
  3534. thread_id = '".intval($thread_id)."'";
  3535. Database::query($sql);
  3536. }
  3537. /**
  3538. * The relies counter gets increased every time somebody replies to the thread
  3539. *
  3540. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3541. * @version february 2006, dokeos 1.8
  3542. * @param string $last_post_id
  3543. * @param string $post_date
  3544. */
  3545. function updateThreadInfo($thread_id, $last_post_id, $post_date)
  3546. {
  3547. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  3548. $course_id = api_get_course_int_id();
  3549. $sql = "UPDATE $table_threads SET
  3550. thread_replies = thread_replies+1,
  3551. thread_last_post = '".Database::escape_string($last_post_id)."',
  3552. thread_date = '".Database::escape_string($post_date)."'
  3553. WHERE
  3554. c_id = $course_id AND
  3555. thread_id='".Database::escape_string($thread_id)."'"; // this needs to be cleaned first
  3556. Database::query($sql);
  3557. }
  3558. /**
  3559. * This function is called when the user is not allowed in this forum/thread/...
  3560. * @return bool display message of "not allowed"
  3561. *
  3562. * @deprecated use api_not_allowed()
  3563. *
  3564. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3565. * @version february 2006, dokeos 1.8
  3566. */
  3567. function forum_not_allowed_here()
  3568. {
  3569. Display::addFlash(Display::return_message(get_lang('NotAllowedHere'), 'error'));
  3570. Display :: display_footer();
  3571. return false;
  3572. }
  3573. /**
  3574. * This function is used to find all the information about what's new in the forum tool
  3575. * @return void
  3576. *
  3577. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3578. * @version february 2006, dokeos 1.8
  3579. */
  3580. function get_whats_new()
  3581. {
  3582. $userId = api_get_user_id();
  3583. $course_id = api_get_course_int_id();
  3584. if (empty($course_id) || empty($userId)) {
  3585. return false;
  3586. }
  3587. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3588. $tracking_last_tool_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3589. $tool = TOOL_FORUM;
  3590. $lastForumAccess = Session::read('last_forum_access');
  3591. if (!$lastForumAccess) {
  3592. $sql = "SELECT * FROM $tracking_last_tool_access
  3593. WHERE
  3594. access_user_id = $userId AND
  3595. c_id = $course_id AND
  3596. access_tool = '".Database::escape_string($tool)."'";
  3597. $result = Database::query($sql);
  3598. $row = Database::fetch_array($result);
  3599. Session::write('last_forum_access', $row['access_date']);
  3600. $lastForumAccess = $row['access_date'];
  3601. }
  3602. $whatsNew = Session::read('whatsnew_post_info');
  3603. if (!$whatsNew) {
  3604. if ($lastForumAccess != '') {
  3605. $postInfo = array();
  3606. $sql = "SELECT * FROM $table_posts
  3607. WHERE
  3608. c_id = $course_id AND
  3609. visible = 1 AND
  3610. post_date > '".Database::escape_string($lastForumAccess)."'";
  3611. $result = Database::query($sql);
  3612. while ($row = Database::fetch_array($result)) {
  3613. $postInfo[$row['forum_id']][$row['thread_id']][$row['post_id']] = $row['post_date'];
  3614. }
  3615. Session::write('whatsnew_post_info', $postInfo);
  3616. }
  3617. }
  3618. }
  3619. /**
  3620. * This function approves a post = change
  3621. *
  3622. * @param int $post_id the id of the post that will be deleted
  3623. * @param string $action make the post visible or invisible
  3624. * @return string language variable
  3625. *
  3626. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3627. * @version february 2006, dokeos 1.8
  3628. */
  3629. function approve_post($post_id, $action)
  3630. {
  3631. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3632. $course_id = api_get_course_int_id();
  3633. if ($action == 'invisible') {
  3634. $visibility_value = 0;
  3635. }
  3636. if ($action == 'visible') {
  3637. $visibility_value = 1;
  3638. handle_mail_cue('post', $post_id);
  3639. }
  3640. $sql = "UPDATE $table_posts SET
  3641. visible='".Database::escape_string($visibility_value)."'
  3642. WHERE c_id = $course_id AND post_id='".Database::escape_string($post_id)."'";
  3643. $return = Database::query($sql);
  3644. if ($return) {
  3645. return 'PostVisibilityChanged';
  3646. }
  3647. }
  3648. /**
  3649. * This function retrieves all the unapproved messages for a given forum
  3650. * This is needed to display the icon that there are unapproved messages in that thread (only the courseadmin can see this)
  3651. *
  3652. * @param $forum_id the forum where we want to know the unapproved messages of
  3653. * @return array returns
  3654. *
  3655. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3656. * @version february 2006, dokeos 1.8
  3657. */
  3658. function get_unaproved_messages($forum_id)
  3659. {
  3660. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3661. $course_id = api_get_course_int_id();
  3662. $return_array = array();
  3663. $sql = "SELECT DISTINCT thread_id FROM $table_posts
  3664. WHERE
  3665. c_id = $course_id AND
  3666. forum_id='".Database::escape_string($forum_id)."' AND
  3667. visible='0' ";
  3668. $result = Database::query($sql);
  3669. while ($row = Database::fetch_array($result)) {
  3670. $return_array[] = $row['thread_id'];
  3671. }
  3672. return $return_array;
  3673. }
  3674. /**
  3675. * This function sends the notification mails to everybody who stated that they wanted to be informed when a new post
  3676. * was added to a given thread.
  3677. *
  3678. * @param array reply information
  3679. * @return void
  3680. *
  3681. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3682. * @version february 2006, dokeos 1.8
  3683. */
  3684. function send_notification_mails($forumId, $thread_id, $reply_info)
  3685. {
  3686. $table = Database::get_course_table(TABLE_FORUM_MAIL_QUEUE);
  3687. // First we need to check if
  3688. // 1. the forum category is visible
  3689. // 2. the forum is visible
  3690. // 3. the thread is visible
  3691. // 4. the reply is visible (=when there is)
  3692. $current_thread = get_thread_information($forumId, $thread_id);
  3693. $current_forum = get_forum_information($current_thread['forum_id'], $current_thread['c_id']);
  3694. $current_forum_category = null;
  3695. if (isset($current_forum['forum_category'])) {
  3696. $current_forum_category = get_forumcategory_information(
  3697. $current_forum['forum_category']
  3698. );
  3699. }
  3700. if ($current_thread['visibility'] == '1' &&
  3701. $current_forum['visibility'] == '1' &&
  3702. ($current_forum_category && $current_forum_category['visibility'] == '1') &&
  3703. $current_forum['approval_direct_post'] != '1'
  3704. ) {
  3705. $send_mails = true;
  3706. } else {
  3707. $send_mails = false;
  3708. }
  3709. // The forum category, the forum, the thread and the reply are visible to the user
  3710. if ($send_mails) {
  3711. if (!empty($forumId)) {
  3712. send_notifications($forumId, $thread_id);
  3713. }
  3714. } else {
  3715. $table_notification = Database::get_course_table(TABLE_FORUM_NOTIFICATION);
  3716. if (isset($current_forum['forum_id'])) {
  3717. $sql = "SELECT * FROM $table_notification
  3718. WHERE
  3719. c_id = ".api_get_course_int_id()." AND
  3720. (
  3721. forum_id = '".intval($current_forum['forum_id'])."' OR
  3722. thread_id = '".intval($thread_id)."'
  3723. ) ";
  3724. $result = Database::query($sql);
  3725. $user_id = api_get_user_id();
  3726. while ($row = Database::fetch_array($result)) {
  3727. $sql = "INSERT INTO $table (c_id, thread_id, post_id, user_id)
  3728. VALUES (".api_get_course_int_id().", '".intval($thread_id)."', '".intval($reply_info['new_post_id'])."', '$user_id' )";
  3729. Database::query($sql);
  3730. }
  3731. }
  3732. }
  3733. }
  3734. /**
  3735. * This function is called whenever something is made visible because there might
  3736. * be new posts and the user might have indicated that (s)he wanted to be
  3737. * informed about the new posts by mail.
  3738. *
  3739. * @param string Content type (post, thread, forum, forum_category)
  3740. * @param int Item DB ID
  3741. * @param string $content
  3742. * @param integer $id
  3743. * @return string language variable
  3744. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3745. * @version february 2006, dokeos 1.8
  3746. */
  3747. function handle_mail_cue($content, $id)
  3748. {
  3749. $table_mailcue = Database :: get_course_table(TABLE_FORUM_MAIL_QUEUE);
  3750. $table_forums = Database :: get_course_table(TABLE_FORUM);
  3751. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  3752. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3753. $table_users = Database :: get_main_table(TABLE_MAIN_USER);
  3754. $course_id = api_get_course_int_id();
  3755. /* If the post is made visible we only have to send mails to the people
  3756. who indicated that they wanted to be informed for that thread.*/
  3757. if ($content == 'post') {
  3758. // Getting the information about the post (need the thread_id).
  3759. $post_info = get_post_information($id);
  3760. $thread_id = intval($post_info['thread_id']);
  3761. // Sending the mail to all the users that wanted to be informed for replies on this thread.
  3762. $sql = "SELECT users.firstname, users.lastname, users.user_id, users.email
  3763. FROM $table_mailcue mailcue, $table_posts posts, $table_users users
  3764. WHERE
  3765. posts.c_id = $course_id AND
  3766. mailcue.c_id = $course_id AND
  3767. posts.thread_id='$thread_id'
  3768. AND posts.post_notification='1'
  3769. AND mailcue.thread_id='$thread_id'
  3770. AND users.user_id=posts.poster_id
  3771. AND users.active=1
  3772. GROUP BY users.email";
  3773. $result = Database::query($sql);
  3774. while ($row = Database::fetch_array($result)) {
  3775. send_mail($row, get_thread_information($post_info['forum_id'], $post_info['thread_id']));
  3776. }
  3777. } elseif ($content == 'thread') {
  3778. // Sending the mail to all the users that wanted to be informed for replies on this thread.
  3779. $sql = "SELECT users.firstname, users.lastname, users.user_id, users.email, posts.forum_id
  3780. FROM $table_mailcue mailcue, $table_posts posts, $table_users users
  3781. WHERE
  3782. posts.c_id = $course_id AND
  3783. mailcue.c_id = $course_id AND
  3784. posts.thread_id = ".intval($id)."
  3785. AND posts.post_notification='1'
  3786. AND mailcue.thread_id = ".intval($id)."
  3787. AND users.user_id=posts.poster_id
  3788. AND users.active=1
  3789. GROUP BY users.email";
  3790. $result = Database::query($sql);
  3791. while ($row = Database::fetch_array($result)) {
  3792. send_mail($row, get_thread_information($row['forum_id'], $id));
  3793. }
  3794. // Deleting the relevant entries from the mailcue.
  3795. $sql = "DELETE FROM $table_mailcue
  3796. WHERE c_id = $course_id AND thread_id='".Database::escape_string($id)."'";
  3797. Database::query($sql);
  3798. } elseif ($content == 'forum') {
  3799. $sql = "SELECT thread_id FROM $table_threads
  3800. WHERE c_id = $course_id AND forum_id='".Database::escape_string($id)."'";
  3801. $result = Database::query($sql);
  3802. while ($row = Database::fetch_array($result)) {
  3803. handle_mail_cue('thread', $row['thread_id']);
  3804. }
  3805. } elseif ($content == 'forum_category') {
  3806. $sql = "SELECT forum_id FROM $table_forums
  3807. WHERE c_id = $course_id AND forum_category ='".Database::escape_string($id)."'";
  3808. $result = Database::query($sql);
  3809. while ($row = Database::fetch_array($result)) {
  3810. handle_mail_cue('forum', $row['forum_id']);
  3811. }
  3812. } else {
  3813. return get_lang('Error');
  3814. }
  3815. }
  3816. /**
  3817. * This function sends the mails for the mail notification
  3818. *
  3819. * @param array
  3820. * @param array
  3821. * @return void
  3822. *
  3823. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3824. * @version february 2006, dokeos 1.8
  3825. */
  3826. function send_mail($user_info = array(), $thread_information = array())
  3827. {
  3828. $_course = api_get_course_info();
  3829. $user_id = api_get_user_id();
  3830. $subject = get_lang('NewForumPost').' - '.$_course['official_code'];
  3831. if (isset($thread_information) && is_array($thread_information)) {
  3832. $thread_link = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$thread_information['forum_id'].'&thread='.$thread_information['thread_id'];
  3833. }
  3834. $email_body = get_lang('Dear').' '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS).", <br />\n\r";
  3835. $email_body .= get_lang('NewForumPost')."\n";
  3836. $email_body .= get_lang('Course').': '.$_course['name'].' - ['.$_course['official_code']."] - <br />\n";
  3837. $email_body .= get_lang('YouWantedToStayInformed')."<br />\n";
  3838. $email_body .= get_lang('ThreadCanBeFoundHere')." : <br /><a href=\"".$thread_link."\">".$thread_link."</a>\n";
  3839. if ($user_info['user_id'] <> $user_id) {
  3840. MessageManager::send_message($user_info['user_id'], $subject, $email_body, [], [], null, null, null, null, $user_id);
  3841. }
  3842. }
  3843. /**
  3844. * This function displays the form for moving a thread to a different (already existing) forum
  3845. * @return void HTML
  3846. *
  3847. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3848. * @version february 2006, dokeos 1.8
  3849. */
  3850. function move_thread_form()
  3851. {
  3852. $gradebook = Security::remove_XSS($_GET['gradebook']);
  3853. $form = new FormValidator(
  3854. 'movepost',
  3855. 'post',
  3856. api_get_self().'?forum='.intval($_GET['forum']).'&gradebook='.$gradebook.'&thread='.intval($_GET['thread']).'&action='.Security::remove_XSS($_GET['action']).'&'.api_get_cidreq()
  3857. );
  3858. // The header for the form
  3859. $form->addElement('header', get_lang('MoveThread'));
  3860. // Invisible form: the thread_id
  3861. $form->addElement('hidden', 'thread_id', intval($_GET['thread']));
  3862. // the fora
  3863. $forum_categories = get_forum_categories();
  3864. $forums = get_forums();
  3865. $htmlcontent = '<div class="row">
  3866. <div class="label">
  3867. <span class="form_required">*</span>'.get_lang('MoveTo').'
  3868. </div>
  3869. <div class="formw">';
  3870. $htmlcontent .= '<select name="forum">';
  3871. foreach ($forum_categories as $key => $category) {
  3872. $htmlcontent .= '<optgroup label="'.$category['cat_title'].'">';
  3873. foreach ($forums as $key => $forum) {
  3874. if (isset($forum['forum_category'])) {
  3875. if ($forum['forum_category'] == $category['cat_id']) {
  3876. $htmlcontent .= '<option value="'.$forum['forum_id'].'">'.$forum['forum_title'].'</option>';
  3877. }
  3878. }
  3879. }
  3880. $htmlcontent .= '</optgroup>';
  3881. }
  3882. $htmlcontent .= "</select>";
  3883. $htmlcontent .= ' </div>
  3884. </div>';
  3885. $form->addElement('html', $htmlcontent);
  3886. // The OK button
  3887. $form->addButtonSave(get_lang('MoveThread'), 'SubmitForum');
  3888. // Validation or display
  3889. if ($form->validate()) {
  3890. $values = $form->exportValues();
  3891. if (isset($_POST['forum'])) {
  3892. store_move_thread($values);
  3893. }
  3894. } else {
  3895. $form->display();
  3896. }
  3897. }
  3898. /**
  3899. * This function displays the form for moving a post message to a different (already existing) or a new thread.
  3900. * @return void HTML
  3901. *
  3902. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3903. * @version february 2006, dokeos 1.8
  3904. */
  3905. function move_post_form()
  3906. {
  3907. $gradebook = Security::remove_XSS($_GET['gradebook']);
  3908. // initiate the object
  3909. $form = new FormValidator('movepost', 'post', api_get_self().'?'.api_get_cidreq().'&forum='.Security::remove_XSS($_GET['forum']).'&thread='.Security::remove_XSS($_GET['thread']).'&gradebook='.$gradebook.'&post='.Security::remove_XSS($_GET['post']).'&action='.Security::remove_XSS($_GET['action']).'&post='.Security::remove_XSS($_GET['post']));
  3910. // The header for the form
  3911. $form->addElement('header', '', get_lang('MovePost'));
  3912. // Invisible form: the post_id
  3913. $form->addElement('hidden', 'post_id', intval($_GET['post']));
  3914. // Dropdown list: Threads of this forum
  3915. $threads = get_threads($_GET['forum']);
  3916. //my_print_r($threads);
  3917. $threads_list[0] = get_lang('ANewThread');
  3918. foreach ($threads as $key => $value) {
  3919. $threads_list[$value['thread_id']] = $value['thread_title'];
  3920. }
  3921. $form->addElement('select', 'thread', get_lang('MoveToThread'), $threads_list);
  3922. $form->applyFilter('thread', 'html_filter');
  3923. // The OK button
  3924. $form->addButtonSave(get_lang('MovePost'), 'submit');
  3925. // Setting the rules
  3926. $form->addRule('thread', get_lang('ThisFieldIsRequired'), 'required');
  3927. // Validation or display
  3928. if ($form->validate()) {
  3929. $values = $form->exportValues();
  3930. store_move_post($values);
  3931. } else {
  3932. $form->display();
  3933. }
  3934. }
  3935. /**
  3936. *
  3937. * @param array
  3938. * @return string HTML language variable
  3939. *
  3940. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3941. * @version february 2006, dokeos 1.8
  3942. */
  3943. function store_move_post($values)
  3944. {
  3945. $_course = api_get_course_info();
  3946. $course_id = api_get_course_int_id();
  3947. $table_forums = Database :: get_course_table(TABLE_FORUM);
  3948. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  3949. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3950. if ($values['thread'] == '0') {
  3951. $current_post = get_post_information($values['post_id']);
  3952. // Storing a new thread.
  3953. $params = [
  3954. 'c_id' => $course_id,
  3955. 'thread_title' => $current_post['post_title'],
  3956. 'forum_id' => $current_post['forum_id'],
  3957. 'thread_poster_id' => $current_post['poster_id'],
  3958. 'thread_poster_name' => $current_post['poster_name'],
  3959. 'thread_last_post' => $values['post_id'],
  3960. 'thread_date' => $current_post['post_date'],
  3961. ];
  3962. $new_thread_id = Database::insert($table_threads, $params);
  3963. api_item_property_update(
  3964. $_course,
  3965. TOOL_FORUM_THREAD,
  3966. $new_thread_id,
  3967. 'visible',
  3968. $current_post['poster_id']
  3969. );
  3970. // Moving the post to the newly created thread.
  3971. $sql = "UPDATE $table_posts SET thread_id='".intval($new_thread_id)."', post_parent_id = NULL
  3972. WHERE c_id = $course_id AND post_id='".intval($values['post_id'])."'";
  3973. Database::query($sql);
  3974. // Resetting the parent_id of the thread to 0 for all those who had this moved post as parent.
  3975. $sql = "UPDATE $table_posts SET post_parent_id = NULL
  3976. WHERE c_id = $course_id AND post_parent_id='".intval($values['post_id'])."'";
  3977. Database::query($sql);
  3978. // Updating updating the number of threads in the forum.
  3979. $sql = "UPDATE $table_forums SET forum_threads=forum_threads+1
  3980. WHERE c_id = $course_id AND forum_id='".intval($current_post['forum_id'])."'";
  3981. Database::query($sql);
  3982. // Resetting the last post of the old thread and decreasing the number of replies and the thread.
  3983. $sql = "SELECT * FROM $table_posts
  3984. WHERE c_id = $course_id AND thread_id='".intval($current_post['thread_id'])."'
  3985. ORDER BY post_id DESC";
  3986. $result = Database::query($sql);
  3987. $row = Database::fetch_array($result);
  3988. $sql = "UPDATE $table_threads SET
  3989. thread_last_post='".$row['post_id']."',
  3990. thread_replies=thread_replies-1
  3991. WHERE
  3992. c_id = $course_id AND
  3993. thread_id='".intval($current_post['thread_id'])."'";
  3994. Database::query($sql);
  3995. } else {
  3996. // Moving to the chosen thread.
  3997. $sql = "SELECT thread_id FROM ".$table_posts."
  3998. WHERE c_id = $course_id AND post_id = '".$values['post_id']."' ";
  3999. $result = Database::query($sql);
  4000. $row = Database::fetch_array($result);
  4001. $original_thread_id = $row['thread_id'];
  4002. $sql = "SELECT thread_last_post FROM ".$table_threads."
  4003. WHERE c_id = $course_id AND thread_id = '".$original_thread_id."' ";
  4004. $result = Database::query($sql);
  4005. $row = Database::fetch_array($result);
  4006. $thread_is_last_post = $row['thread_last_post'];
  4007. // If is this thread, update the thread_last_post with the last one.
  4008. if ($thread_is_last_post == $values['post_id']) {
  4009. $sql = "SELECT post_id FROM ".$table_posts."
  4010. WHERE c_id = $course_id AND thread_id = '".$original_thread_id."' AND post_id <> '".$values['post_id']."'
  4011. ORDER BY post_date DESC LIMIT 1";
  4012. $result = Database::query($sql);
  4013. $row = Database::fetch_array($result);
  4014. $thread_new_last_post = $row['post_id'];
  4015. $sql = "UPDATE ".$table_threads." SET thread_last_post = '".$thread_new_last_post."'
  4016. WHERE c_id = $course_id AND thread_id = '".$original_thread_id."' ";
  4017. Database::query($sql);
  4018. }
  4019. $sql = "UPDATE $table_threads SET thread_replies=thread_replies-1
  4020. WHERE c_id = $course_id AND thread_id='".$original_thread_id."'";
  4021. Database::query($sql);
  4022. // moving to the chosen thread
  4023. $sql = "UPDATE $table_posts SET thread_id='".intval($_POST['thread'])."', post_parent_id = NULL
  4024. WHERE c_id = $course_id AND post_id='".intval($values['post_id'])."'";
  4025. Database::query($sql);
  4026. // resetting the parent_id of the thread to 0 for all those who had this moved post as parent
  4027. $sql = "UPDATE $table_posts SET post_parent_id = NULL
  4028. WHERE c_id = $course_id AND post_parent_id='".intval($values['post_id'])."'";
  4029. Database::query($sql);
  4030. $sql = "UPDATE $table_threads SET thread_replies=thread_replies+1
  4031. WHERE c_id = $course_id AND thread_id='".intval($_POST['thread'])."'";
  4032. Database::query($sql);
  4033. }
  4034. return get_lang('ThreadMoved');
  4035. }
  4036. /**
  4037. *
  4038. * @param array
  4039. * @return string HTML language variable
  4040. *
  4041. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  4042. * @version february 2006, dokeos 1.8
  4043. */
  4044. function store_move_thread($values)
  4045. {
  4046. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  4047. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  4048. $courseId = api_get_course_int_id();
  4049. $sessionId = api_get_session_id();
  4050. $forumId = intval($_POST['forum']);
  4051. $threadId = intval($_POST['thread_id']);
  4052. $forumInfo = get_forums($forumId);
  4053. // Change the thread table: Setting the forum_id to the new forum.
  4054. $sql = "UPDATE $table_threads SET forum_id = $forumId
  4055. WHERE c_id = $courseId AND thread_id = $threadId";
  4056. Database::query($sql);
  4057. // Changing all the posts of the thread: setting the forum_id to the new forum.
  4058. $sql = "UPDATE $table_posts SET forum_id = $forumId
  4059. WHERE c_id = $courseId AND thread_id= $threadId";
  4060. Database::query($sql);
  4061. // Fix group id, if forum is moved to a different group
  4062. if (!empty($forumInfo['to_group_id'])) {
  4063. $groupId = $forumInfo['to_group_id'];
  4064. $item = api_get_item_property_info($courseId, TABLE_FORUM_THREAD, $threadId, $sessionId, $groupId);
  4065. $table = Database:: get_course_table(TABLE_ITEM_PROPERTY);
  4066. $sessionCondition = api_get_session_condition($sessionId);
  4067. if (!empty($item)) {
  4068. if ($item['to_group_id'] != $groupId) {
  4069. $sql = "UPDATE $table
  4070. SET to_group_id = $groupId
  4071. WHERE
  4072. tool = '".TABLE_FORUM_THREAD."' AND
  4073. c_id = $courseId AND
  4074. ref = ".$item['ref']."
  4075. $sessionCondition
  4076. ";
  4077. Database::query($sql);
  4078. }
  4079. } else {
  4080. $sql = "UPDATE $table
  4081. SET to_group_id = $groupId
  4082. WHERE
  4083. tool = '".TABLE_FORUM_THREAD."' AND
  4084. c_id = $courseId AND
  4085. ref = ".$threadId."
  4086. $sessionCondition
  4087. ";
  4088. Database::query($sql);
  4089. }
  4090. }
  4091. return get_lang('ThreadMoved');
  4092. }
  4093. /**
  4094. * Prepares a string for displaying by highlighting the search results inside, if any.
  4095. * @param string $input The input string.
  4096. * @return string The same string with highlighted hits inside.
  4097. *
  4098. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, February 2006 - the initial version.
  4099. * @author Ivan Tcholakov, March 2011 - adaptation for Chamilo LMS.
  4100. */
  4101. function prepare4display($input)
  4102. {
  4103. static $highlightcolors = array('yellow', '#33CC33', '#3399CC', '#9999FF', '#33CC33');
  4104. static $search;
  4105. if (!isset($search)) {
  4106. if (isset($_POST['search_term'])) {
  4107. $search = $_POST['search_term']; // No html at all.
  4108. } elseif (isset($_GET['search'])) {
  4109. $search = $_GET['search'];
  4110. } else {
  4111. $search = '';
  4112. }
  4113. }
  4114. if (!empty($search)) {
  4115. if (strstr($search, '+')) {
  4116. $search_terms = explode('+', $search);
  4117. } else {
  4118. $search_terms[] = trim($search);
  4119. }
  4120. $counter = 0;
  4121. foreach ($search_terms as $key => $search_term) {
  4122. $input = api_preg_replace('/'.preg_quote(trim($search_term), '/').'/i', '<span style="background-color: '.$highlightcolors[$counter].'">$0</span>', $input);
  4123. $counter++;
  4124. }
  4125. }
  4126. // TODO: Security should be implemented outside this function.
  4127. // Change this to COURSEMANAGERLOWSECURITY or COURSEMANAGER to lower filtering and allow more styles (see comments of Security::remove_XSS() method to learn about other levels).
  4128. return Security::remove_XSS($input, STUDENT, true);
  4129. }
  4130. /**
  4131. * Display the search form for the forum and display the search results
  4132. * @return void display an HTML search results
  4133. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4134. * @version march 2008, dokeos 1.8.5
  4135. */
  4136. function forum_search()
  4137. {
  4138. $form = new FormValidator('forumsearch', 'post', 'forumsearch.php?'.api_get_cidreq());
  4139. // Setting the form elements.
  4140. $form->addElement('header', '', get_lang('ForumSearch'));
  4141. $form->addElement('text', 'search_term', get_lang('SearchTerm'), array('autofocus'));
  4142. $form->applyFilter('search_term', 'html_filter');
  4143. $form->addElement('static', 'search_information', '', get_lang('ForumSearchInformation'));
  4144. $form->addButtonSearch(get_lang('Search'));
  4145. // Setting the rules.
  4146. $form->addRule('search_term', get_lang('ThisFieldIsRequired'), 'required');
  4147. $form->addRule('search_term', get_lang('TooShort'), 'minlength', 3);
  4148. // Validation or display.
  4149. if ($form->validate()) {
  4150. $values = $form->exportValues();
  4151. $form->setDefaults($values);
  4152. $form->display();
  4153. // Display the search results.
  4154. display_forum_search_results(stripslashes($values['search_term']));
  4155. } else {
  4156. $form->display();
  4157. }
  4158. }
  4159. /**
  4160. * Display the search results
  4161. * @param string
  4162. * @param string $search_term
  4163. * @return void display the results
  4164. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4165. * @version march 2008, dokeos 1.8.5
  4166. */
  4167. function display_forum_search_results($search_term)
  4168. {
  4169. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  4170. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  4171. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  4172. $session_id = api_get_session_id();
  4173. $gradebook = Security::remove_XSS($_GET['gradebook']);
  4174. $course_id = api_get_course_int_id();
  4175. // Defining the search strings as an array.
  4176. if (strstr($search_term, '+')) {
  4177. $search_terms = explode('+', $search_term);
  4178. } else {
  4179. $search_terms[] = $search_term;
  4180. }
  4181. // Search restriction.
  4182. foreach ($search_terms as $value) {
  4183. $search_restriction[] = "
  4184. (
  4185. posts.post_title LIKE '%".Database::escape_string(trim($value))."%' OR
  4186. posts.post_text LIKE '%".Database::escape_string(trim($value))."%'
  4187. )";
  4188. }
  4189. $sessionCondition = api_get_session_condition($session_id, true, false, 'item_property.session_id');
  4190. $sql = "SELECT posts.*
  4191. FROM $table_posts posts INNER JOIN $table_threads threads
  4192. ON (posts.thread_id = threads.thread_id AND posts.c_id = threads.c_id)
  4193. INNER JOIN $table_item_property item_property
  4194. ON (item_property.ref = threads.thread_id AND item_property.c_id = threads.c_id)
  4195. WHERE
  4196. posts.c_id = $course_id AND
  4197. item_property.c_id = $course_id AND
  4198. item_property.visibility = 1
  4199. $sessionCondition AND
  4200. posts.visible = 1 AND
  4201. item_property.tool = '".TOOL_FORUM_THREAD."' AND
  4202. ".implode(' AND ', $search_restriction)."
  4203. GROUP BY posts.post_id";
  4204. // Getting all the information of the forum categories.
  4205. $forum_categories_list = get_forum_categories();
  4206. // Getting all the information of the forums.
  4207. $forum_list = get_forums();
  4208. $result = Database::query($sql);
  4209. $search_results = [];
  4210. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4211. $forumId = $row['forum_id'];
  4212. $forumData = get_forums($forumId);
  4213. $category = isset($forum_categories_list[$forumData['forum_category']]) ? $forum_categories_list[$forumData['forum_category']] : null;
  4214. $display_result = false;
  4215. /*
  4216. We only show it when
  4217. 1. forum category is visible
  4218. 2. forum is visible
  4219. 3. thread is visible (to do)
  4220. 4. post is visible
  4221. */
  4222. if (!api_is_allowed_to_edit(null, true)) {
  4223. if (!empty($category)) {
  4224. if ($category['visibility'] == '1' && $forumData['visibility'] == '1') {
  4225. $display_result = true;
  4226. }
  4227. } else {
  4228. if ($forumData['visible'] == '1') {
  4229. $display_result = true;
  4230. }
  4231. }
  4232. } else {
  4233. $display_result = true;
  4234. }
  4235. if ($display_result) {
  4236. $categoryName = !empty($category) ? $category['cat_title'] : '';
  4237. $search_results_item = '<li><a href="viewforumcategory.php?'.api_get_cidreq().'&forumcategory='.$forumData['forum_category'].'&search='.urlencode($search_term).'">'.
  4238. prepare4display($categoryName).'</a> &gt; ';
  4239. $search_results_item .= '<a href="viewforum.php?'.api_get_cidreq().'&forum='.$forumId.'&search='.urlencode($search_term).'">'.
  4240. prepare4display($forum_list[$row['forum_id']]['forum_title']).'</a> &gt; ';
  4241. $search_results_item .= '<a href="viewthread.php?'.api_get_cidreq().'&forum='.$forumId.'&gradebook='.$gradebook.'&thread='.$row['thread_id'].'&search='.urlencode($search_term).'">'.
  4242. prepare4display($row['post_title']).'</a>';
  4243. $search_results_item .= '<br />';
  4244. if (api_strlen($row['post_title']) > 200) {
  4245. $search_results_item .= prepare4display(api_substr(strip_tags($row['post_title']), 0, 200)).'...';
  4246. } else {
  4247. $search_results_item .= prepare4display($row['post_title']);
  4248. }
  4249. $search_results_item .= '</li>';
  4250. $search_results[] = $search_results_item;
  4251. }
  4252. }
  4253. echo '<legend>'.count($search_results).' '.get_lang('ForumSearchResults').'</legend>';
  4254. echo '<ol>';
  4255. if ($search_results) {
  4256. echo implode($search_results);
  4257. }
  4258. echo '</ol>';
  4259. }
  4260. /**
  4261. * Return the link to the forum search page
  4262. *
  4263. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4264. * @version April 2008, dokeos 1.8.5
  4265. */
  4266. function search_link()
  4267. {
  4268. $return = '';
  4269. $origin = api_get_origin();
  4270. if ($origin != 'learnpath') {
  4271. $return = '<a href="forumsearch.php?'.api_get_cidreq().'&action=search"> ';
  4272. $return .= Display::return_icon('search.png', get_lang('Search'), '', ICON_SIZE_MEDIUM).'</a>';
  4273. if (!empty($_GET['search'])) {
  4274. $return .= ': '.Security::remove_XSS($_GET['search']).' ';
  4275. $url = api_get_self().'?';
  4276. $url_parameter = array();
  4277. foreach ($_GET as $key => $value) {
  4278. if ($key != 'search') {
  4279. $url_parameter[] = Security::remove_XSS($key).'='.Security::remove_XSS($value);
  4280. }
  4281. }
  4282. $url = $url.implode('&', $url_parameter);
  4283. $return .= '<a href="'.$url.'">'.Display::return_icon('delete.gif', get_lang('RemoveSearchResults')).'</a>';
  4284. }
  4285. }
  4286. return $return;
  4287. }
  4288. /**
  4289. * This function adds an attachment file into a forum
  4290. * @param string $file_comment a comment about file
  4291. * @param int $last_id from forum_post table
  4292. * @return false|null
  4293. */
  4294. function add_forum_attachment_file($file_comment, $last_id)
  4295. {
  4296. $_course = api_get_course_info();
  4297. $agenda_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  4298. if (!isset($_FILES['user_upload'])) {
  4299. return false;
  4300. }
  4301. $fileCount = count($_FILES['user_upload']['name']);
  4302. $filesData = [];
  4303. if (!is_array($_FILES['user_upload']['name'])) {
  4304. $filesData[] = $_FILES['user_upload'];
  4305. } else {
  4306. $fileKeys = array_keys($_FILES['user_upload']);
  4307. for ($i = 0; $i < $fileCount; $i++) {
  4308. foreach ($fileKeys as $key) {
  4309. $filesData[$i][$key] = $_FILES['user_upload'][$key][$i];
  4310. }
  4311. }
  4312. }
  4313. foreach ($filesData as $attachment) {
  4314. if (empty($attachment['name'])) {
  4315. continue;
  4316. }
  4317. $upload_ok = process_uploaded_file($attachment);
  4318. if (!$upload_ok) {
  4319. continue;
  4320. }
  4321. $course_dir = $_course['path'] . '/upload/forum';
  4322. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  4323. $updir = $sys_course_path . $course_dir;
  4324. // Try to add an extension to the file if it hasn't one.
  4325. $new_file_name = add_ext_on_mime(
  4326. stripslashes($attachment['name']),
  4327. $attachment['type']
  4328. );
  4329. // User's file name
  4330. $file_name = $attachment['name'];
  4331. if (!filter_extension($new_file_name)) {
  4332. Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
  4333. return;
  4334. }
  4335. $new_file_name = uniqid('');
  4336. $new_path = $updir . '/' . $new_file_name;
  4337. $result = @move_uploaded_file($attachment['tmp_name'], $new_path);
  4338. $safe_file_comment = Database::escape_string($file_comment);
  4339. $safe_file_name = Database::escape_string($file_name);
  4340. $safe_new_file_name = Database::escape_string($new_file_name);
  4341. $last_id = intval($last_id);
  4342. // Storing the attachments if any.
  4343. if (!$result) {
  4344. return;
  4345. }
  4346. $last_id_file = Database::insert(
  4347. $agenda_forum_attachment,
  4348. [
  4349. 'c_id' => api_get_course_int_id(),
  4350. 'filename' => $safe_file_name,
  4351. 'comment' => $safe_file_comment,
  4352. 'path' => $safe_new_file_name,
  4353. 'post_id' => $last_id,
  4354. 'size' => intval($attachment['size']),
  4355. ]
  4356. );
  4357. api_item_property_update(
  4358. $_course,
  4359. TOOL_FORUM_ATTACH,
  4360. $last_id_file,
  4361. 'ForumAttachmentAdded',
  4362. api_get_user_id()
  4363. );
  4364. }
  4365. }
  4366. /**
  4367. * This function edits an attachment file into a forum
  4368. * @param string $file_comment a comment about file
  4369. * @param int $post_id
  4370. * @param int $id_attach attachment file Id
  4371. * @return void
  4372. */
  4373. function edit_forum_attachment_file($file_comment, $post_id, $id_attach)
  4374. {
  4375. $_course = api_get_course_info();
  4376. $table_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  4377. $course_id = api_get_course_int_id();
  4378. $fileCount = count($_FILES['user_upload']['name']);
  4379. $filesData = [];
  4380. if (!is_array($_FILES['user_upload']['name'])) {
  4381. $filesData[] = $_FILES['user_upload'];
  4382. } else {
  4383. $fileKeys = array_keys($_FILES['user_upload']);
  4384. for ($i = 0; $i < $fileCount; $i++) {
  4385. foreach ($fileKeys as $key) {
  4386. $filesData[$i][$key] = $_FILES['user_upload'][$key][$i];
  4387. }
  4388. }
  4389. }
  4390. foreach ($filesData as $attachment) {
  4391. if (empty($attachment['name'])) {
  4392. continue;
  4393. }
  4394. $upload_ok = process_uploaded_file($attachment);
  4395. if (!$upload_ok) {
  4396. continue;
  4397. }
  4398. $course_dir = $_course['path'].'/upload/forum';
  4399. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  4400. $updir = $sys_course_path.$course_dir;
  4401. // Try to add an extension to the file if it hasn't one.
  4402. $new_file_name = add_ext_on_mime(stripslashes($attachment['name']), $attachment['type']);
  4403. // User's file name
  4404. $file_name = $attachment['name'];
  4405. if (!filter_extension($new_file_name)) {
  4406. Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
  4407. } else {
  4408. $new_file_name = uniqid('');
  4409. $new_path = $updir.'/'.$new_file_name;
  4410. $result = @move_uploaded_file($attachment['tmp_name'], $new_path);
  4411. $safe_file_comment = Database::escape_string($file_comment);
  4412. $safe_file_name = Database::escape_string($file_name);
  4413. $safe_new_file_name = Database::escape_string($new_file_name);
  4414. $safe_post_id = (int) $post_id;
  4415. $safe_id_attach = (int) $id_attach;
  4416. // Storing the attachments if any.
  4417. if ($result) {
  4418. $sql = "UPDATE $table_forum_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', post_id = '$safe_post_id', size ='".$attachment['size']."'
  4419. WHERE c_id = $course_id AND id = '$safe_id_attach'";
  4420. Database::query($sql);
  4421. api_item_property_update($_course, TOOL_FORUM_ATTACH, $safe_id_attach, 'ForumAttachmentUpdated', api_get_user_id());
  4422. }
  4423. }
  4424. }
  4425. }
  4426. /**
  4427. * Show a list with all the attachments according to the post's id
  4428. * @param int $post_id
  4429. * @return array with the post info
  4430. * @author Julio Montoya
  4431. * @version avril 2008, dokeos 1.8.5
  4432. */
  4433. function get_attachment($post_id)
  4434. {
  4435. $forum_table_attachment = Database :: get_course_table(TABLE_FORUM_ATTACHMENT);
  4436. $course_id = api_get_course_int_id();
  4437. $row = array();
  4438. $post_id = intval($post_id);
  4439. $sql = "SELECT iid, path, filename, comment
  4440. FROM $forum_table_attachment
  4441. WHERE c_id = $course_id AND post_id = $post_id";
  4442. $result = Database::query($sql);
  4443. if (Database::num_rows($result) != 0) {
  4444. $row = Database::fetch_array($result);
  4445. }
  4446. return $row;
  4447. }
  4448. /**
  4449. * @param int $postId
  4450. *
  4451. * @return array
  4452. */
  4453. function getAllAttachment($postId)
  4454. {
  4455. $forumAttachmentTable = Database :: get_course_table(TABLE_FORUM_ATTACHMENT);
  4456. $courseId = api_get_course_int_id();
  4457. $postId = intval($postId);
  4458. $columns = array('iid', 'path', 'filename', 'comment');
  4459. $conditions = array(
  4460. 'where' => array(
  4461. 'c_id = ? AND post_id = ?' => array($courseId, $postId),
  4462. ),
  4463. );
  4464. $array = Database::select(
  4465. $columns,
  4466. $forumAttachmentTable,
  4467. $conditions,
  4468. 'all',
  4469. 'ASSOC'
  4470. );
  4471. return $array;
  4472. }
  4473. /**
  4474. * Delete the all the attachments from the DB and the file according to the post's id or attach id(optional)
  4475. * @param int $post_id
  4476. * @param int $id_attach
  4477. * @param bool $display to show or not result message
  4478. * @return integer
  4479. * @author Julio Montoya
  4480. * @version october 2014, chamilo 1.9.8
  4481. */
  4482. function delete_attachment($post_id, $id_attach = 0, $display = true)
  4483. {
  4484. $_course = api_get_course_info();
  4485. $forum_table_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  4486. $course_id = api_get_course_int_id();
  4487. $cond = (!empty($id_attach)) ? " iid = " . (int) $id_attach . "" : " post_id = " . (int) $post_id . "";
  4488. $sql = "SELECT path FROM $forum_table_attachment WHERE c_id = $course_id AND $cond";
  4489. $res = Database::query($sql);
  4490. $row = Database::fetch_array($res);
  4491. $course_dir = $_course['path'] . '/upload/forum';
  4492. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  4493. $updir = $sys_course_path . $course_dir;
  4494. $my_path = isset($row['path']) ? $row['path'] : null;
  4495. $file = $updir . '/' . $my_path;
  4496. if (Security::check_abs_path($file, $updir)) {
  4497. @unlink($file);
  4498. }
  4499. // Delete from forum_attachment table.
  4500. $sql = "DELETE FROM $forum_table_attachment WHERE c_id = $course_id AND $cond ";
  4501. $result = Database::query($sql);
  4502. if ($result !== false) {
  4503. $affectedRows = Database::affected_rows($result);
  4504. } else {
  4505. $affectedRows = 0;
  4506. }
  4507. // Update item_property.
  4508. api_item_property_update($_course, TOOL_FORUM_ATTACH, $id_attach, 'ForumAttachmentDelete', api_get_user_id());
  4509. if (!empty($result) && !empty($id_attach) && $display) {
  4510. $message = get_lang('AttachmentFileDeleteSuccess');
  4511. Display::display_confirmation_message($message);
  4512. }
  4513. return $affectedRows;
  4514. }
  4515. /**
  4516. * This function gets all the forum information of the all the forum of the group
  4517. *
  4518. * @param integer $groupId the id of the group we need the fora of (see forum.forum_of_group)
  4519. * @return array
  4520. *
  4521. * @todo this is basically the same code as the get_forums function. Consider merging the two.
  4522. */
  4523. function get_forums_of_group($groupId)
  4524. {
  4525. $table_forums = Database :: get_course_table(TABLE_FORUM);
  4526. $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  4527. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  4528. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  4529. $course_id = api_get_course_int_id();
  4530. $groupId = (int) $groupId;
  4531. // Student
  4532. // Select all the forum information of all forums (that are visible to students).
  4533. $sql = "SELECT * FROM $table_forums forum
  4534. INNER JOIN $table_item_property item_properties
  4535. ON (forum.forum_id = item_properties.ref AND item_properties.c_id = forum.c_id)
  4536. WHERE
  4537. forum.forum_of_group = $groupId AND
  4538. forum.c_id = $course_id AND
  4539. item_properties.c_id = $course_id AND
  4540. item_properties.visibility = 1 AND
  4541. item_properties.tool = '".TOOL_FORUM."'
  4542. ORDER BY forum.forum_order ASC";
  4543. // Select the number of threads of the forums (only the threads that are visible).
  4544. $sql2 = "SELECT
  4545. count(thread_id) AS number_of_threads,
  4546. threads.forum_id
  4547. FROM $table_threads threads
  4548. INNER JOIN $table_item_property item_properties
  4549. ON (threads.thread_id = item_properties.ref AND item_properties.c_id = threads.c_id)
  4550. WHERE
  4551. threads.c_id = $course_id AND
  4552. item_properties.c_id = $course_id AND
  4553. item_properties.visibility = 1 AND
  4554. item_properties.tool='".TOOL_FORUM_THREAD."'
  4555. GROUP BY threads.forum_id";
  4556. // Select the number of posts of the forum (post that are visible and that are in a thread that is visible).
  4557. $sql3 = "SELECT count(post_id) AS number_of_posts, posts.forum_id
  4558. FROM $table_posts posts
  4559. INNER JOIN $table_threads threads
  4560. ON (posts.thread_id = threads.thread_id AND posts.c_id = threads.c_id)
  4561. INNER JOIN $table_item_property item_properties
  4562. ON (threads.thread_id = item_properties.ref AND item_properties.c_id = threads.c_id)
  4563. WHERE
  4564. posts.visible=1 AND
  4565. posts.c_id = $course_id AND
  4566. item_properties.c_id = $course_id AND
  4567. threads.c_id = $course_id AND
  4568. item_properties.visibility = 1 AND
  4569. item_properties.tool='".TOOL_FORUM_THREAD."'
  4570. GROUP BY threads.forum_id";
  4571. // Course Admin
  4572. if (api_is_allowed_to_edit()) {
  4573. // Select all the forum information of all forums (that are not deleted).
  4574. $sql = "SELECT *
  4575. FROM $table_forums forum INNER JOIN $table_item_property item_properties
  4576. ON (forum.forum_id = item_properties.ref AND item_properties.c_id = forum.c_id)
  4577. WHERE
  4578. forum.forum_of_group = $groupId AND
  4579. forum.c_id = $course_id AND
  4580. item_properties.c_id = $course_id AND
  4581. item_properties.visibility <> 2 AND
  4582. item_properties.tool = '".TOOL_FORUM."'
  4583. ORDER BY forum_order ASC";
  4584. // Select the number of threads of the forums (only the threads that are not deleted).
  4585. $sql2 = "SELECT count(thread_id) AS number_of_threads, threads.forum_id
  4586. FROM $table_threads threads INNER JOIN $table_item_property item_properties
  4587. ON (threads.thread_id=item_properties.ref AND item_properties.c_id = threads.c_id)
  4588. WHERE
  4589. threads.c_id = $course_id AND
  4590. item_properties.c_id = $course_id AND
  4591. item_properties.visibility <> 2 AND
  4592. item_properties.tool='".TOOL_FORUM_THREAD."'
  4593. GROUP BY threads.forum_id";
  4594. // Select the number of posts of the forum.
  4595. $sql3 = "SELECT count(post_id) AS number_of_posts, forum_id
  4596. FROM $table_posts
  4597. WHERE c_id = $course_id
  4598. GROUP BY forum_id";
  4599. }
  4600. // Handling all the forum information.
  4601. $result = Database::query($sql);
  4602. $forum_list = array();
  4603. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4604. $forum_list[$row['forum_id']] = $row;
  4605. }
  4606. // Handling the thread count information.
  4607. $result2 = Database::query($sql2);
  4608. while ($row2 = Database::fetch_array($result2, 'ASSOC')) {
  4609. if (is_array($forum_list)) {
  4610. if (array_key_exists($row2['forum_id'], $forum_list)) {
  4611. $forum_list[$row2['forum_id']]['number_of_threads'] = $row2['number_of_threads'];
  4612. }
  4613. }
  4614. }
  4615. // Handling the post count information.
  4616. $result3 = Database::query($sql3);
  4617. while ($row3 = Database::fetch_array($result3, 'ASSOC')) {
  4618. if (is_array($forum_list)) {
  4619. if (array_key_exists($row3['forum_id'], $forum_list)) {
  4620. // This is needed because sql3 takes also the deleted forums into account.
  4621. $forum_list[$row3['forum_id']]['number_of_posts'] = $row3['number_of_posts'];
  4622. }
  4623. }
  4624. }
  4625. // Finding the last post information
  4626. // (last_post_id, last_poster_id, last_post_date, last_poster_name, last_poster_lastname, last_poster_firstname).
  4627. if (!empty($forum_list)) {
  4628. foreach ($forum_list as $key => $value) {
  4629. $last_post_info_of_forum = get_last_post_information($key, api_is_allowed_to_edit());
  4630. if ($last_post_info_of_forum) {
  4631. $forum_list[$key]['last_post_id'] = $last_post_info_of_forum['last_post_id'];
  4632. $forum_list[$key]['last_poster_id'] = $last_post_info_of_forum['last_poster_id'];
  4633. $forum_list[$key]['last_post_date'] = $last_post_info_of_forum['last_post_date'];
  4634. $forum_list[$key]['last_poster_name'] = $last_post_info_of_forum['last_poster_name'];
  4635. $forum_list[$key]['last_poster_lastname'] = $last_post_info_of_forum['last_poster_lastname'];
  4636. $forum_list[$key]['last_poster_firstname'] = $last_post_info_of_forum['last_poster_firstname'];
  4637. }
  4638. }
  4639. }
  4640. return $forum_list;
  4641. }
  4642. /**
  4643. * This function stores which users have to be notified of which forums or threads
  4644. *
  4645. * @param string $content does the user want to be notified about a forum or about a thread
  4646. * @param integer $id the id of the forum or thread
  4647. * @return string language variable
  4648. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4649. * @version May 2008, dokeos 1.8.5
  4650. * @since May 2008, dokeos 1.8.5
  4651. */
  4652. function set_notification($content, $id, $add_only = false)
  4653. {
  4654. $_user = api_get_user_info();
  4655. // Database table definition
  4656. $table_notification = Database::get_course_table(TABLE_FORUM_NOTIFICATION);
  4657. $course_id = api_get_course_int_id();
  4658. // Which database field do we have to store the id in?
  4659. if ($content == 'forum') {
  4660. $database_field = 'forum_id';
  4661. } else {
  4662. $database_field = 'thread_id';
  4663. }
  4664. // First we check if the notification is already set for this.
  4665. $sql = "SELECT * FROM $table_notification
  4666. WHERE
  4667. c_id = $course_id AND
  4668. $database_field = '".Database::escape_string($id)."' AND
  4669. user_id = '".intval($_user['user_id'])."'";
  4670. $result = Database::query($sql);
  4671. $total = Database::num_rows($result);
  4672. // If the user did not indicate that (s)he wanted to be notified already
  4673. // then we store the notification request (to prevent double notification requests).
  4674. if ($total <= 0) {
  4675. $sql = "INSERT INTO $table_notification (c_id, $database_field, user_id)
  4676. VALUES (".$course_id.", '".Database::escape_string($id)."','".intval($_user['user_id'])."')";
  4677. Database::query($sql);
  4678. Session::erase('forum_notification');
  4679. get_notifications_of_user(0, true);
  4680. return get_lang('YouWillBeNotifiedOfNewPosts');
  4681. } else {
  4682. if (!$add_only) {
  4683. $sql = "DELETE FROM $table_notification
  4684. WHERE
  4685. c_id = $course_id AND
  4686. $database_field = '".Database::escape_string($id)."' AND
  4687. user_id = '".intval($_user['user_id'])."'";
  4688. Database::query($sql);
  4689. Session::erase('forum_notification');
  4690. get_notifications_of_user(0, true);
  4691. return get_lang('YouWillNoLongerBeNotifiedOfNewPosts');
  4692. }
  4693. }
  4694. }
  4695. /**
  4696. * This function retrieves all the email adresses of the users who wanted to be notified
  4697. * about a new post in a certain forum or thread
  4698. *
  4699. * @param string $content does the user want to be notified about a forum or about a thread
  4700. * @param integer $id the id of the forum or thread
  4701. * @return array returns
  4702. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4703. * @version May 2008, dokeos 1.8.5
  4704. * @since May 2008, dokeos 1.8.5
  4705. */
  4706. function get_notifications($content, $id)
  4707. {
  4708. // Database table definition
  4709. $table_users = Database::get_main_table(TABLE_MAIN_USER);
  4710. $table_notification = Database::get_course_table(TABLE_FORUM_NOTIFICATION);
  4711. $course_id = api_get_course_int_id();
  4712. // Which database field contains the notification?
  4713. if ($content == 'forum') {
  4714. $database_field = 'forum_id';
  4715. } else {
  4716. $database_field = 'thread_id';
  4717. }
  4718. $sql = "SELECT user.user_id, user.firstname, user.lastname, user.email, user.user_id user
  4719. FROM $table_users user, $table_notification notification
  4720. WHERE notification.c_id = $course_id AND user.active = 1 AND
  4721. user.user_id = notification.user_id AND
  4722. notification.$database_field= '".Database::escape_string($id)."'";
  4723. $result = Database::query($sql);
  4724. $return = array();
  4725. while ($row = Database::fetch_array($result)) {
  4726. $return['user'.$row['user_id']] = array('email' => $row['email'], 'user_id' => $row['user_id']);
  4727. }
  4728. return $return;
  4729. }
  4730. /**
  4731. * Get all the users who need to receive a notification of a new post (those subscribed to
  4732. * the forum or the thread)
  4733. *
  4734. * @param integer $forum_id the id of the forum
  4735. * @param integer $thread_id the id of the thread
  4736. * @param integer $post_id the id of the post
  4737. * @return false|null
  4738. *
  4739. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4740. * @version May 2008, dokeos 1.8.5
  4741. * @since May 2008, dokeos 1.8.5
  4742. */
  4743. function send_notifications($forum_id = 0, $thread_id = 0, $post_id = 0)
  4744. {
  4745. $_course = api_get_course_info();
  4746. $forum_id = (int) $forum_id;
  4747. // The content of the mail
  4748. $thread_link = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum_id.'&thread='.$thread_id;
  4749. // Users who subscribed to the forum
  4750. if ($forum_id != 0) {
  4751. $users_to_be_notified_by_forum = get_notifications('forum', $forum_id);
  4752. } else {
  4753. return false;
  4754. }
  4755. $current_thread = get_thread_information($forum_id, $thread_id);
  4756. $current_forum = get_forum_information($current_thread['forum_id']);
  4757. $subject = get_lang('NewForumPost').' - '.$_course['official_code'].' - '.$current_forum['forum_title'].' - '.$current_thread['thread_title'];
  4758. // User who subscribed to the thread
  4759. if ($thread_id != 0) {
  4760. $users_to_be_notified_by_thread = get_notifications('thread', $thread_id);
  4761. }
  4762. // Merging the two
  4763. $users_to_be_notified = array_merge($users_to_be_notified_by_forum, $users_to_be_notified_by_thread);
  4764. $sender_id = api_get_user_id();
  4765. if (is_array($users_to_be_notified)) {
  4766. foreach ($users_to_be_notified as $value) {
  4767. $user_info = api_get_user_info($value['user_id']);
  4768. $email_body = get_lang('Dear').' '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS).", <br />\n\r";
  4769. $email_body .= get_lang('NewForumPost').": ".$current_forum['forum_title'].' - '.$current_thread['thread_title']." <br />\n";
  4770. $email_body .= get_lang('Course').': '.$_course['name'].' - ['.$_course['official_code']."] <br />\n";
  4771. $email_body .= get_lang('YouWantedToStayInformed')."<br />\n";
  4772. $email_body .= get_lang('ThreadCanBeFoundHere').': <br /> <a href="'.$thread_link.'">'.$thread_link."</a>\n";
  4773. MessageManager::send_message_simple(
  4774. $value['user_id'], $subject, $email_body, $sender_id
  4775. );
  4776. }
  4777. }
  4778. }
  4779. /**
  4780. * Get all the notification subscriptions of the user
  4781. * = which forums and which threads does the user wants to be informed of when a new
  4782. * post is added to this thread
  4783. *
  4784. * @param integer $user_id the user_id of a user (default = 0 => the current user)
  4785. * @param boolean $force force get the notification subscriptions (even if the information is already in the session
  4786. * @return array returns
  4787. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  4788. * @version May 2008, dokeos 1.8.5
  4789. * @since May 2008, dokeos 1.8.5
  4790. */
  4791. function get_notifications_of_user($user_id = 0, $force = false)
  4792. {
  4793. // Database table definition
  4794. $table_notification = Database::get_course_table(TABLE_FORUM_NOTIFICATION);
  4795. $course_id = api_get_course_int_id();
  4796. if (empty($course_id) || $course_id == -1) {
  4797. return null;
  4798. }
  4799. if ($user_id == 0) {
  4800. $user_id = api_get_user_id();
  4801. }
  4802. if (!isset($_SESSION['forum_notification']) ||
  4803. $_SESSION['forum_notification']['course'] != $course_id ||
  4804. $force = true
  4805. ) {
  4806. $_SESSION['forum_notification']['course'] = $course_id;
  4807. $sql = "SELECT * FROM $table_notification
  4808. WHERE c_id = $course_id AND user_id='".intval($user_id)."'";
  4809. $result = Database::query($sql);
  4810. while ($row = Database::fetch_array($result)) {
  4811. if (!is_null($row['forum_id'])) {
  4812. $_SESSION['forum_notification']['forum'][] = $row['forum_id'];
  4813. }
  4814. if (!is_null($row['thread_id'])) {
  4815. $_SESSION['forum_notification']['thread'][] = $row['thread_id'];
  4816. }
  4817. }
  4818. }
  4819. }
  4820. /**
  4821. * This function counts the number of post inside a thread
  4822. * @param int $thread_id
  4823. * @return int the number of post inside a thread
  4824. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  4825. * @version octubre 2008, dokeos 1.8
  4826. */
  4827. function count_number_of_post_in_thread($thread_id)
  4828. {
  4829. $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
  4830. $course_id = api_get_course_int_id();
  4831. if (empty($course_id)) {
  4832. return 0;
  4833. }
  4834. $sql = "SELECT count(*) count FROM $table_posts
  4835. WHERE
  4836. c_id = $course_id AND
  4837. thread_id='".intval($thread_id)."' ";
  4838. $result = Database::query($sql);
  4839. $count = 0;
  4840. if (Database::num_rows($result) > 0) {
  4841. $row = Database::fetch_array($result);
  4842. $count = $row['count'];
  4843. }
  4844. return $count;
  4845. }
  4846. /**
  4847. * This function counts the number of post inside a thread user
  4848. * @param int $thread_id
  4849. * @param int $user_id
  4850. *
  4851. * @return int the number of post inside a thread user
  4852. */
  4853. function count_number_of_post_for_user_thread($thread_id, $user_id)
  4854. {
  4855. $table_posts = Database::get_course_table(TABLE_FORUM_POST);
  4856. $course_id = api_get_course_int_id();
  4857. $sql = "SELECT count(iid) as count
  4858. FROM $table_posts
  4859. WHERE c_id = $course_id AND
  4860. thread_id=".intval($thread_id)." AND
  4861. poster_id = ".intval($user_id)." AND visible = 1 ";
  4862. $result = Database::query($sql);
  4863. $count = 0;
  4864. if (Database::num_rows($result) > 0) {
  4865. $count = Database::fetch_array($result);
  4866. $count = $count['count'];
  4867. }
  4868. return $count;
  4869. }
  4870. /**
  4871. * This function counts the number of user register in course
  4872. * @param int $course_id Course ID
  4873. * @deprecated use CourseManager::get_users_count_in_course
  4874. * @return int the number of user register in course
  4875. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  4876. * @version octubre 2008, dokeos 1.8
  4877. */
  4878. function count_number_of_user_in_course($course_id)
  4879. {
  4880. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4881. $sql = "SELECT * FROM $table
  4882. WHERE c_id ='".intval($course_id)."' ";
  4883. $result = Database::query($sql);
  4884. return count(Database::store_result($result));
  4885. }
  4886. /**
  4887. * This function retrieves information of statistical
  4888. * @param int $thread_id
  4889. * @param int $user_id
  4890. * @param int $course_id
  4891. *
  4892. * @return array the information of statistical
  4893. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  4894. * @version oct 2008, dokeos 1.8
  4895. */
  4896. function get_statistical_information($thread_id, $user_id, $course_id)
  4897. {
  4898. $result = array();
  4899. $courseInfo = api_get_course_info_by_id($course_id);
  4900. $result['user_course'] = CourseManager::get_users_count_in_course($courseInfo['code']);
  4901. $result['post'] = count_number_of_post_in_thread($thread_id);
  4902. $result['user_post'] = count_number_of_post_for_user_thread($thread_id, $user_id);
  4903. return $result;
  4904. }
  4905. /**
  4906. * This function return the posts inside a thread from a given user
  4907. * @param string $course_code
  4908. * @param int $thread_id
  4909. * @param int $user_id
  4910. *
  4911. * @return array posts inside a thread
  4912. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  4913. * @version oct 2008, dokeos 1.8
  4914. */
  4915. function get_thread_user_post($course_code, $thread_id, $user_id)
  4916. {
  4917. $table_posts = Database::get_course_table(TABLE_FORUM_POST);
  4918. $table_users = Database::get_main_table(TABLE_MAIN_USER);
  4919. $thread_id = intval($thread_id);
  4920. $user_id = intval($user_id);
  4921. $course_info = api_get_user_info($course_code);
  4922. $course_id = $course_info['real_id'];
  4923. if (empty($course_id)) {
  4924. $course_id = api_get_course_int_id();
  4925. }
  4926. $sql = "SELECT * FROM $table_posts posts
  4927. LEFT JOIN $table_users users
  4928. ON posts.poster_id=users.user_id
  4929. WHERE
  4930. posts.c_id = $course_id AND
  4931. posts.thread_id='$thread_id'
  4932. AND posts.poster_id='$user_id'
  4933. ORDER BY posts.post_id ASC";
  4934. $result = Database::query($sql);
  4935. $post_list = array();
  4936. while ($row = Database::fetch_array($result)) {
  4937. $row['status'] = '1';
  4938. $post_list[] = $row;
  4939. $sql = "SELECT * FROM $table_posts posts
  4940. LEFT JOIN $table_users users
  4941. ON (posts.poster_id=users.user_id)
  4942. WHERE
  4943. posts.c_id = $course_id AND
  4944. posts.thread_id='$thread_id'
  4945. AND posts.post_parent_id='".$row['post_id']."'
  4946. ORDER BY posts.post_id ASC";
  4947. $result2 = Database::query($sql);
  4948. while ($row2 = Database::fetch_array($result2)) {
  4949. $row2['status'] = '0';
  4950. $post_list[] = $row2;
  4951. }
  4952. }
  4953. return $post_list;
  4954. }
  4955. /**
  4956. * This function get the name of an thread by id
  4957. * @param int thread_id
  4958. * @return String
  4959. * @author Christian Fasanando
  4960. * @author Julio Montoya <gugli100@gmail.com> Adding security
  4961. */
  4962. function get_name_thread_by_id($thread_id)
  4963. {
  4964. $t_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
  4965. $course_id = api_get_course_int_id();
  4966. $sql = "SELECT thread_title
  4967. FROM $t_forum_thread
  4968. WHERE c_id = $course_id AND thread_id = '".intval($thread_id)."' ";
  4969. $result = Database::query($sql);
  4970. $row = Database::fetch_array($result);
  4971. return $row[0];
  4972. }
  4973. /**
  4974. * This function gets all the post written by an user
  4975. * @param int $user_id
  4976. * @param string $course_code
  4977. *
  4978. * @return string
  4979. */
  4980. function get_all_post_from_user($user_id, $course_code)
  4981. {
  4982. $j = 0;
  4983. $forums = get_forums('', $course_code);
  4984. krsort($forums);
  4985. $forum_results = '';
  4986. foreach ($forums as $forum) {
  4987. if ($forum['visibility'] == 0) {
  4988. continue;
  4989. }
  4990. if ($j <= 4) {
  4991. $threads = get_threads($forum['forum_id']);
  4992. if (is_array($threads)) {
  4993. $i = 0;
  4994. $hand_forums = '';
  4995. $post_counter = 0;
  4996. foreach ($threads as $thread) {
  4997. if ($thread['visibility'] == 0) {
  4998. continue;
  4999. }
  5000. if ($i <= 4) {
  5001. $post_list = get_thread_user_post_limit($course_code, $thread['thread_id'], $user_id, 1);
  5002. $post_counter = count($post_list);
  5003. if (is_array($post_list) && count($post_list) > 0) {
  5004. $hand_forums.= '<div id="social-thread">';
  5005. $hand_forums.= Display::return_icon('thread.png', get_lang('Thread'), '', ICON_SIZE_MEDIUM);
  5006. $hand_forums.= '&nbsp;'.Security::remove_XSS($thread['thread_title'], STUDENT);
  5007. $hand_forums.= '</div>';
  5008. foreach ($post_list as $posts) {
  5009. $hand_forums.= '<div id="social-post">';
  5010. $hand_forums.= '<strong>'.Security::remove_XSS($posts['post_title'], STUDENT).'</strong>';
  5011. $hand_forums.= '<br / >';
  5012. $hand_forums.= Security::remove_XSS($posts['post_text'], STUDENT);
  5013. $hand_forums.= '</div>';
  5014. $hand_forums.= '<br / >';
  5015. }
  5016. }
  5017. }
  5018. $i++;
  5019. }
  5020. $forum_results .='<div id="social-forum">';
  5021. $forum_results .='<div class="clear"></div><br />';
  5022. $forum_results .='<div id="social-forum-title">'.
  5023. Display::return_icon('forum.gif', get_lang('Forum')).'&nbsp;'.Security::remove_XSS($forum['forum_title'], STUDENT).
  5024. '<div style="float:right;margin-top:-35px">
  5025. <a href="../forum/viewforum.php?'.api_get_cidreq_params($course_code).'&forum='.$forum['forum_id'].' " >'.
  5026. get_lang('SeeForum').'
  5027. </a>
  5028. </div></div>';
  5029. $forum_results .='<br / >';
  5030. if ($post_counter > 0) {
  5031. $forum_results .=$hand_forums;
  5032. }
  5033. $forum_results .='</div>';
  5034. }$j++;
  5035. }
  5036. }
  5037. return $forum_results;
  5038. }
  5039. /**
  5040. * @param string $course_code
  5041. * @param int $thread_id
  5042. * @param int $user_id
  5043. * @param int $limit
  5044. *
  5045. * @return array
  5046. */
  5047. function get_thread_user_post_limit($course_code, $thread_id, $user_id, $limit = 10)
  5048. {
  5049. $table_posts = Database::get_course_table(TABLE_FORUM_POST);
  5050. $table_users = Database::get_main_table(TABLE_MAIN_USER);
  5051. $course_info = api_get_course_info($course_code);
  5052. $course_id = $course_info['real_id'];
  5053. $sql = "SELECT * FROM $table_posts posts
  5054. LEFT JOIN $table_users users
  5055. ON posts.poster_id=users.user_id
  5056. WHERE
  5057. posts.c_id = $course_id AND
  5058. posts.thread_id='".Database::escape_string($thread_id)."'
  5059. AND posts.poster_id='".Database::escape_string($user_id)."'
  5060. ORDER BY posts.post_id DESC LIMIT $limit ";
  5061. $result = Database::query($sql);
  5062. $post_list = array();
  5063. while ($row = Database::fetch_array($result)) {
  5064. $row['status'] = '1';
  5065. $post_list[] = $row;
  5066. }
  5067. return $post_list;
  5068. }
  5069. /**
  5070. * @param string $user_id
  5071. * @param int $courseId
  5072. * @param int $sessionId
  5073. *
  5074. * @return array
  5075. */
  5076. function getForumCreatedByUser($user_id, $courseId, $sessionId)
  5077. {
  5078. $items = api_get_item_property_list_by_tool_by_user(
  5079. $user_id,
  5080. 'forum',
  5081. $courseId,
  5082. $sessionId
  5083. );
  5084. $courseInfo = api_get_course_info_by_id($courseId);
  5085. $forumList = array();
  5086. if (!empty($items)) {
  5087. foreach ($items as $forum) {
  5088. $forumInfo = get_forums(
  5089. $forum['ref'],
  5090. $courseInfo['code'],
  5091. true,
  5092. $sessionId
  5093. );
  5094. $forumList[] = array(
  5095. $forumInfo['forum_title'],
  5096. api_get_local_time($forum['insert_date']),
  5097. api_get_local_time($forum['lastedit_date']),
  5098. );
  5099. }
  5100. }
  5101. return $forumList;
  5102. }
  5103. /**
  5104. * This function builds an array of all the posts in a given thread
  5105. * where the key of the array is the post_id
  5106. * It also adds an element children to the array which itself is an array
  5107. * that contains all the id's of the first-level children
  5108. * @return array $rows containing all the information on the posts of a thread
  5109. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  5110. */
  5111. function calculate_children($rows)
  5112. {
  5113. $sorted_rows = array(0 => array());
  5114. if (!empty($rows)) {
  5115. foreach ($rows as $row) {
  5116. $rows_with_children[$row['post_id']] = $row;
  5117. $rows_with_children[$row['post_parent_id']]['children'][] = $row['post_id'];
  5118. }
  5119. $rows = $rows_with_children;
  5120. forumRecursiveSort($rows, $sorted_rows);
  5121. unset($sorted_rows[0]);
  5122. }
  5123. return $sorted_rows;
  5124. }
  5125. /**
  5126. * @param $rows
  5127. * @param $threads
  5128. * @param int $seed
  5129. * @param int $indent
  5130. */
  5131. function forumRecursiveSort($rows, &$threads, $seed = 0, $indent = 0)
  5132. {
  5133. if ($seed > 0) {
  5134. $threads[$rows[$seed]['post_id']] = $rows[$seed];
  5135. $threads[$rows[$seed]['post_id']]['indent_cnt'] = $indent;
  5136. $indent++;
  5137. }
  5138. if (isset($rows[$seed]['children'])) {
  5139. foreach ($rows[$seed]['children'] as $child) {
  5140. forumRecursiveSort($rows, $threads, $child, $indent);
  5141. }
  5142. }
  5143. }
  5144. /**
  5145. * Update forum attachment data, used to update comment and post ID.
  5146. * @param $array Array (field => value) to update forum attachment row.
  5147. * @param $id Attach ID to find row to update.
  5148. * @param null $courseId Course ID to find row to update.
  5149. * @return int Number of affected rows.
  5150. */
  5151. function editAttachedFile($array, $id, $courseId = null) {
  5152. // Init variables
  5153. $setString = '';
  5154. $id = intval($id);
  5155. $courseId = intval($courseId);
  5156. if (empty($courseId)) {
  5157. // $courseId can be null, use api method
  5158. $courseId= api_get_course_int_id();
  5159. }
  5160. /*
  5161. * Check if Attachment ID and Course ID are greater than zero
  5162. * and array of field values is not empty
  5163. */
  5164. if ($id > 0 && $courseId > 0 && !empty($array) && is_array($array)) {
  5165. foreach($array as $key => &$item) {
  5166. $item = Database::escape_string($item);
  5167. $setString .= $key . ' = "' .$item . '", ';
  5168. }
  5169. // Delete last comma
  5170. $setString = substr($setString, 0, strlen($setString) - 2);
  5171. $forumAttachmentTable = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  5172. $sql = "UPDATE $forumAttachmentTable SET $setString WHERE c_id = $courseId AND id = $id";
  5173. $result = Database::query($sql);
  5174. if ($result !== false) {
  5175. $affectedRows = Database::affected_rows($result);
  5176. if ($affectedRows > 0) {
  5177. /*
  5178. * If exist in $_SESSION variable, then delete them from it
  5179. * because they would be deprecated
  5180. */
  5181. if (!empty($_SESSION['forum']['upload_file'][$courseId][$id])) {
  5182. unset($_SESSION['forum']['upload_file'][$courseId][$id]);
  5183. }
  5184. }
  5185. return $affectedRows;
  5186. }
  5187. }
  5188. return 0;
  5189. }
  5190. /**
  5191. * Return a table where the attachments will be set
  5192. * @param int $postId Forum Post ID
  5193. *
  5194. * @return string The Forum Attachments Ajax Table
  5195. */
  5196. function getAttachmentsAjaxTable($postId = 0)
  5197. {
  5198. // Init variables
  5199. $postId = intval($postId);
  5200. $courseId = api_get_course_int_id();
  5201. $attachIds = getAttachmentIdsByPostId($postId, $courseId);
  5202. $fileDataContent = '';
  5203. // Update comment to show if form did not pass validation
  5204. if (!empty($_REQUEST['file_ids']) && is_array($_REQUEST['file_ids'])) {
  5205. // 'file_ids is the name from forum attachment ajax form
  5206. foreach ($_REQUEST['file_ids'] as $key => $attachId) {
  5207. if (!empty($_SESSION['forum']['upload_file'][$courseId][$attachId]) &&
  5208. is_array($_SESSION['forum']['upload_file'][$courseId][$attachId])
  5209. ) {
  5210. // If exist forum attachment then update into $_SESSION data
  5211. $_SESSION['forum']['upload_file'][$courseId][$attachId]['comment'] = $_POST['file_comments'][$key];
  5212. }
  5213. }
  5214. }
  5215. // Get data to fill into attachment files table
  5216. if (!empty($_SESSION['forum']['upload_file'][$courseId]) &&
  5217. is_array($_SESSION['forum']['upload_file'][$courseId])
  5218. ) {
  5219. $uploadedFiles = $_SESSION['forum']['upload_file'][$courseId];
  5220. foreach ($uploadedFiles as $k => $uploadedFile) {
  5221. if (!empty($uploadedFile) && in_array($uploadedFile['id'], $attachIds)) {
  5222. // Buil html table including an input with attachmentID
  5223. $fileDataContent .= '<tr id="' . $uploadedFile['id'] . '" ><td>' . $uploadedFile['name'] . '</td><td>' . $uploadedFile['size'] . '</td><td>&nbsp;' . $uploadedFile['result'] .
  5224. ' </td><td> <input style="width:90%;" type="text" value="' . $uploadedFile['comment'] . '" name="file_comments[]"> </td><td>' .
  5225. $uploadedFile['delete'] . '</td>' .
  5226. '<input type="hidden" value="' . $uploadedFile['id'] .'" name="file_ids[]">' . '</tr>';
  5227. } else {
  5228. /*
  5229. * If attachment data is empty, then delete it from $_SESSION
  5230. * because could generate and empty row into html table
  5231. */
  5232. unset($_SESSION['forum']['upload_file'][$courseId][$k]);
  5233. }
  5234. }
  5235. }
  5236. $style = empty($fileDataContent) ? 'display: none;' : '';
  5237. // Forum attachment Ajax table
  5238. $fileData = '
  5239. <div class="control-group " style="'. $style . '">
  5240. <label class="control-label">'.get_lang('AttachmentList').'</label>
  5241. <div class="controls">
  5242. <table id="attachmentFileList" class="files data_table span10">
  5243. <tr>
  5244. <th>'.get_lang('FileName').'</th>
  5245. <th>'.get_lang('Size').'</th>
  5246. <th>'.get_lang('Status').'</th>
  5247. <th>'.get_lang('Comment').'</th>
  5248. <th>'.get_lang('Delete').'</th>
  5249. </tr>
  5250. '.$fileDataContent.'
  5251. </table>
  5252. </div>
  5253. </div>';
  5254. return $fileData;
  5255. }
  5256. /**
  5257. * Return an array of prepared attachment data to build forum attachment table
  5258. * Also, save this array into $_SESSION to do available the attachment data
  5259. * @param int $forumId
  5260. * @param int $threadId
  5261. * @param int $postId
  5262. * @param int $attachId
  5263. * @param int $courseId
  5264. *
  5265. * @return array
  5266. */
  5267. function getAttachedFiles($forumId, $threadId, $postId = 0, $attachId = 0, $courseId = 0)
  5268. {
  5269. $forumId = intval($forumId);
  5270. $courseId = intval($courseId);
  5271. $attachId = intval($attachId);
  5272. $postId = intval($postId);
  5273. $threadId = !empty($threadId) ? intval($threadId) : isset($_REQUEST['thread']) ? intval($_REQUEST['thread']) : '';
  5274. if (empty($courseId)) {
  5275. // $courseId can be null, use api method
  5276. $courseId = api_get_course_int_id();
  5277. }
  5278. if (empty($forumId)) {
  5279. if (!empty($_REQUEST['forum'])) {
  5280. $forumId = intval($_REQUEST['forum']);
  5281. } else {
  5282. // if forum ID is empty, cannot generate delete url
  5283. return array();
  5284. }
  5285. }
  5286. // Check if exist at least one of them to filter forum attachment select query
  5287. if (empty($postId) && empty($attachId)) {
  5288. return array();
  5289. } elseif (empty($postId)) {
  5290. $filter = "AND iid = $attachId";
  5291. } elseif (empty($attachId)) {
  5292. $filter = "AND post_id = $postId";
  5293. } else {
  5294. $filter = "AND post_id = $postId AND iid = $attachId";
  5295. }
  5296. $forumAttachmentTable = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  5297. $sql = "SELECT iid, comment, filename, path, size
  5298. FROM $forumAttachmentTable
  5299. WHERE c_id = $courseId $filter";
  5300. $result = Database::query($sql);
  5301. $json = array();
  5302. if ($result !== false && Database::num_rows($result) > 0) {
  5303. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5304. // name contains an URL to download attachment file and its filename
  5305. $json['name'] = Display::url(
  5306. api_htmlentities($row['filename']),
  5307. api_get_path(WEB_CODE_PATH) . 'forum/download.php?file='.$row['path'].'&'.api_get_cidreq(),
  5308. array('target'=>'_blank', 'class' => 'attachFilename')
  5309. );
  5310. $json['id'] = $row['iid'];
  5311. $json['comment'] = $row['comment'];
  5312. // Format file size
  5313. $json['size'] = format_file_size($row['size']);
  5314. // Check if $row is consistent
  5315. if (!empty($row) && is_array($row)) {
  5316. // Set result as success and bring delete URL
  5317. $json['result'] = Display::return_icon('accept.png', get_lang('Uploaded'));
  5318. $url = api_get_path(WEB_CODE_PATH) . 'forum/viewthread.php?' . api_get_cidreq() . '&action=delete_attach&forum=' . $forumId . '&thread=' . $threadId.'&id_attach=' . $row['iid'];
  5319. $json['delete'] = Display::url(
  5320. Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL),
  5321. $url,
  5322. array('class' => 'deleteLink')
  5323. );
  5324. } else {
  5325. // If not, set an exclamation result
  5326. $json['result'] = Display::return_icon('exclamation.png', get_lang('Error'));
  5327. }
  5328. // Store array data into $_SESSION
  5329. $_SESSION['forum']['upload_file'][$courseId][$json['id']] = $json;
  5330. }
  5331. }
  5332. return $json;
  5333. }
  5334. /**
  5335. * Clear forum attachment data stored in $_SESSION,
  5336. * If is not defined post, it will clear all forum attachment data from course
  5337. * @param int $postId -1 : Clear all attachments from course stored in $_SESSION
  5338. * 0 : Clear attachments from course, except from temporal post "0"
  5339. * but without delete them from file system and database
  5340. * Other values : Clear attachments from course except specified post
  5341. * and delete them from file system and database
  5342. * @param int $courseId : Course ID, if it is null, will use api_get_course_int_id()
  5343. *
  5344. * @return array
  5345. */
  5346. function clearAttachedFiles($postId = null, $courseId = null) {
  5347. // Init variables
  5348. $courseId = intval($courseId);
  5349. $postId = intval($postId);
  5350. $array = array();
  5351. if (empty($courseId)) {
  5352. // $courseId can be null, use api method
  5353. $courseId = api_get_course_int_id();
  5354. }
  5355. if ($postId === -1) {
  5356. // If post ID is -1 then delete course's attachment data from $_SESSION
  5357. if (!empty($_SESSION['forum']['upload_file'][$courseId])) {
  5358. $array = array_keys($_SESSION['forum']['upload_file'][$courseId]);
  5359. unset($_SESSION['forum']['upload_file'][$courseId]);
  5360. }
  5361. } else {
  5362. $attachIds = getAttachmentIdsByPostId($postId, $courseId);
  5363. if (!empty($_SESSION['forum']['upload_file'][$courseId]) &&
  5364. is_array($_SESSION['forum']['upload_file'][$courseId])) {
  5365. foreach ($_SESSION['forum']['upload_file'][$courseId] as $attachId => $attach) {
  5366. if (!in_array($attachId, $attachIds)) {
  5367. // If attach ID is not into specified post, delete attachment
  5368. // Save deleted attachment ID
  5369. $array[] = $attachId;
  5370. if ($postId !== 0) {
  5371. // Post 0 is temporal, delete them from file system and DB
  5372. delete_attachment(0, $attachId, false);
  5373. }
  5374. // Delete attachment data from $_SESSION
  5375. unset($_SESSION['forum']['upload_file'][$courseId][$attachId]);
  5376. }
  5377. }
  5378. }
  5379. }
  5380. return $array;
  5381. }
  5382. /**
  5383. * Returns an array of forum attachment ids into a course and forum post
  5384. * @param int $postId
  5385. * @param int $courseId
  5386. *
  5387. * @return array
  5388. */
  5389. function getAttachmentIdsByPostId($postId, $courseId = null)
  5390. {
  5391. $array = array();
  5392. $courseId = intval($courseId);
  5393. $postId = intval($postId);
  5394. if (empty($courseId)) {
  5395. // $courseId can be null, use api method
  5396. $courseId = api_get_course_int_id();
  5397. }
  5398. if ($courseId > 0) {
  5399. $forumAttachmentTable = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
  5400. $sql = "SELECT id FROM $forumAttachmentTable
  5401. WHERE c_id = $courseId AND post_id = $postId";
  5402. $result = Database::query($sql);
  5403. if ($result !== false && Database::num_rows($result) > 0) {
  5404. while ($row = Database::fetch_array($result,'ASSOC')) {
  5405. $array[] = $row['id'];
  5406. }
  5407. }
  5408. }
  5409. return $array;
  5410. }
  5411. /**
  5412. * Check if the forum category exists looking for its title
  5413. * @param string $title The forum category title
  5414. * @param int $courseId The course ID
  5415. * @param int $sessionId Optional. The session ID
  5416. * @return boolean
  5417. */
  5418. function getForumCategoryByTitle($title, $courseId, $sessionId = 0)
  5419. {
  5420. $sessionId = intval($sessionId);
  5421. $forumCategoryTable = Database::get_course_table(TABLE_FORUM_CATEGORY);
  5422. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  5423. $fakeFrom = "$forumCategoryTable fc
  5424. INNER JOIN $itemProperty ip ";
  5425. if ($sessionId === 0) {
  5426. $fakeFrom .= "
  5427. ON (
  5428. fc.cat_id = ip.ref AND fc.c_id = ip.c_id AND (fc.session_id = ip.session_id OR ip.session_id IS NULL)
  5429. )
  5430. ";
  5431. } else {
  5432. $fakeFrom .= "
  5433. ON (
  5434. fc.cat_id = ip.ref AND fc.c_id = ip.c_id AND fc.session_id = ip.session_id
  5435. )
  5436. ";
  5437. }
  5438. $resultData = Database::select(
  5439. 'fc.*',
  5440. $fakeFrom,
  5441. [
  5442. 'where' => [
  5443. 'ip.visibility != ? AND ' => 2,
  5444. 'ip.tool = ? AND ' => TOOL_FORUM_CATEGORY,
  5445. 'fc.session_id = ? AND ' => $sessionId,
  5446. 'fc.cat_title = ? AND ' => $title,
  5447. 'fc.c_id = ?' => intval($courseId)
  5448. ]
  5449. ],
  5450. 'first'
  5451. );
  5452. if (empty($resultData)) {
  5453. return false;
  5454. }
  5455. return $resultData;
  5456. }
  5457. /**
  5458. * @param array $current_forum
  5459. * @param array $row
  5460. *
  5461. * @return string
  5462. */
  5463. function getPostStatus($current_forum, $row, $addWrapper = true)
  5464. {
  5465. $statusIcon = '';
  5466. if ($current_forum['moderated']) {
  5467. if ($addWrapper) {
  5468. $statusIcon = '<br /><br /><span id="status_post_'.$row['iid'].'">';
  5469. }
  5470. $row['status'] = empty($row['status']) ? 2 : $row['status'];
  5471. $addUrl = false;
  5472. if (api_is_allowed_to_edit(false, true)) {
  5473. $addUrl = true;
  5474. }
  5475. $label = '';
  5476. $icon = '';
  5477. $buttonType = '';
  5478. switch ($row['status']) {
  5479. case CForumPost::STATUS_VALIDATED:
  5480. $label = get_lang('Validated');
  5481. $icon = 'check-circle';
  5482. $buttonType = 'success';
  5483. break;
  5484. case CForumPost::STATUS_WAITING_MODERATION:
  5485. $label = get_lang('WaitingModeration');
  5486. $icon = 'warning';
  5487. $buttonType = 'warning';
  5488. break;
  5489. case CForumPost::STATUS_REJECTED:
  5490. $label = get_lang('Rejected');
  5491. $icon = 'minus-circle';
  5492. $buttonType = 'danger';
  5493. break;
  5494. }
  5495. if ($addUrl) {
  5496. $statusIcon .= Display::toolbarButton(
  5497. $label.'&nbsp;',
  5498. 'javascript:void(0)',
  5499. $icon,
  5500. $buttonType,
  5501. ['class' => 'change_post_status']
  5502. );
  5503. } else {
  5504. $statusIcon .= Display::label(
  5505. Display::returnFontAwesomeIcon($icon).$label,
  5506. $buttonType
  5507. );
  5508. }
  5509. if ($addWrapper) {
  5510. $statusIcon .= '</span>';
  5511. }
  5512. }
  5513. return $statusIcon;
  5514. }
  5515. /**
  5516. * @param array $forumInfo
  5517. * @param int $threadId
  5518. * @param int $status
  5519. * @return mixed
  5520. */
  5521. function getCountPostsWithStatus($status, $forumInfo, $threadId = null)
  5522. {
  5523. $em = Database::getManager();
  5524. $criteria = Criteria::create();
  5525. $criteria
  5526. ->where(Criteria::expr()->eq('status', $status))
  5527. ->andWhere(Criteria::expr()->eq('cId', $forumInfo['c_id']))
  5528. ->andWhere(Criteria::expr()->eq('visible', 1))
  5529. ;
  5530. if (!empty($threadId)) {
  5531. $criteria->andWhere(Criteria::expr()->eq('threadId', $threadId));
  5532. }
  5533. $qb = $em->getRepository('ChamiloCourseBundle:CForumPost')->createQueryBuilder('p');
  5534. $qb->select('count(p.iid)')
  5535. ->addCriteria($criteria);
  5536. return $qb->getQuery()->getSingleScalarResult();
  5537. }
  5538. /**
  5539. * @param array $forum
  5540. * @param array $post
  5541. *
  5542. * @return bool
  5543. */
  5544. function postIsEditableByStudent($forum, $post)
  5545. {
  5546. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  5547. return true;
  5548. }
  5549. if ($forum['moderated'] == 1) {
  5550. if (is_null($post['status'])) {
  5551. return true;
  5552. } else {
  5553. return $post['status'] == CForumPost::STATUS_WAITING_MODERATION;
  5554. }
  5555. } else {
  5556. return true;
  5557. }
  5558. }