forumfunction.inc.php 227 KB

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