main_api.lib.php 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is a code library for Chamilo.
  5. * It is included by default in every Chamilo file (through including the global.inc.php)
  6. *
  7. * @package chamilo.library
  8. */
  9. /**
  10. * Constants declaration
  11. */
  12. // USER STATUS CONSTANTS
  13. /** global status of a user: student */
  14. define('STUDENT', 5);
  15. /** global status of a user: course manager */
  16. define('COURSEMANAGER', 1);
  17. /** global status of a user: session admin */
  18. define('SESSIONADMIN', 3);
  19. /** global status of a user: human ressource manager */
  20. define('DRH', 4);
  21. /** global status of a user: human ressource manager */
  22. define('ANONYMOUS', 6);
  23. /** global status of a user: low security, necessary for inserting data from
  24. * the teacher through HTMLPurifier */
  25. define('COURSEMANAGERLOWSECURITY', 10);
  26. // Table of status
  27. $_status_list[COURSEMANAGER] = 'teacher'; // 1
  28. $_status_list[SESSIONADMIN] = 'session_admin'; // 3
  29. $_status_list[DRH] = 'drh'; // 4
  30. $_status_list[STUDENT] = 'user'; // 5
  31. $_status_list[ANONYMOUS] = 'anonymous'; // 6
  32. // COURSE VISIBILITY CONSTANTS
  33. /** only visible for course admin */
  34. define('COURSE_VISIBILITY_CLOSED', 0);
  35. /** only visible for users registered in the course*/
  36. define('COURSE_VISIBILITY_REGISTERED', 1);
  37. /** Open for all registered users on the platform */
  38. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  39. /** Open for the whole world */
  40. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  41. // SESSION VISIBILITY CONSTANTS
  42. define('SESSION_VISIBLE_READ_ONLY', 1);
  43. define('SESSION_VISIBLE', 2);
  44. define('SESSION_INVISIBLE', 3); // not available
  45. define('SESSION_AVAILABLE', 4);
  46. define('SUBSCRIBE_ALLOWED', 1);
  47. define('SUBSCRIBE_NOT_ALLOWED', 0);
  48. define('UNSUBSCRIBE_ALLOWED', 1);
  49. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  50. // CONSTANTS defining all tools, using the english version
  51. /* When you add a new tool you must add it into function api_get_tools_lists() too */
  52. define('TOOL_DOCUMENT','document');
  53. define('TOOL_THUMBNAIL', 'thumbnail');
  54. define('TOOL_HOTPOTATOES', 'hotpotatoes');
  55. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  56. define('TOOL_LINK', 'link');
  57. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  58. define('TOOL_SEARCH', 'search');
  59. define('TOOL_LEARNPATH', 'learnpath');
  60. define('TOOL_ANNOUNCEMENT', 'announcement');
  61. define('TOOL_FORUM', 'forum');
  62. define('TOOL_THREAD', 'thread');
  63. define('TOOL_POST', 'post');
  64. define('TOOL_DROPBOX', 'dropbox');
  65. define('TOOL_QUIZ', 'quiz');
  66. define('TOOL_USER', 'user');
  67. define('TOOL_GROUP', 'group');
  68. define('TOOL_BLOGS', 'blog_management'); // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be)
  69. define('TOOL_CHAT', 'chat');
  70. define('TOOL_CONFERENCE', 'conference');
  71. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  72. define('TOOL_TRACKING', 'tracking');
  73. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  74. define('TOOL_COURSE_SETTING', 'course_setting');
  75. define('TOOL_BACKUP', 'backup');
  76. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  77. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  78. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  79. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  80. define('TOOL_UPLOAD','file_upload');
  81. define('TOOL_COURSE_MAINTENANCE','course_maintenance');
  82. define('TOOL_VISIO','visio');
  83. define('TOOL_VISIO_CONFERENCE','visio_conference');
  84. define('TOOL_VISIO_CLASSROOM','visio_classroom');
  85. define('TOOL_SURVEY','survey');
  86. define('TOOL_WIKI','wiki');
  87. define('TOOL_GLOSSARY','glossary');
  88. define('TOOL_GRADEBOOK','gradebook');
  89. define('TOOL_NOTEBOOK','notebook');
  90. define('TOOL_ATTENDANCE','attendance');
  91. define('TOOL_COURSE_PROGRESS','course_progress');
  92. // CONSTANTS defining Chamilo interface sections
  93. define('SECTION_CAMPUS', 'mycampus');
  94. define('SECTION_COURSES', 'mycourses');
  95. define('SECTION_MYPROFILE', 'myprofile');
  96. define('SECTION_MYAGENDA', 'myagenda');
  97. define('SECTION_COURSE_ADMIN', 'course_admin');
  98. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  99. define('SECTION_MYGRADEBOOK', 'mygradebook');
  100. define('SECTION_TRACKING','session_my_space');
  101. define('SECTION_SOCIAL', 'social');
  102. define('SECTION_DASHBOARD', 'dashboard');
  103. define('SECTION_REPORTS', 'reports');
  104. define('SECTION_GLOBAL', 'global');
  105. // CONSTANT name for local authentication source
  106. define('PLATFORM_AUTH_SOURCE', 'platform');
  107. // CONSTANT defining the default HotPotatoes files directory
  108. define('DIR_HOTPOTATOES','/HotPotatoes_files');
  109. // event logs types
  110. define('LOG_COURSE_DELETE', 'course_deleted');
  111. define('LOG_COURSE_CREATE', 'course_created');
  112. define('LOG_USER_DELETE', 'user_deleted');
  113. define('LOG_USER_CREATE', 'user_created');
  114. define('LOG_SESSION_CREATE', 'session_created');
  115. define('LOG_SESSION_DELETE', 'session_deleted');
  116. define('LOG_SESSION_CATEGORY_CREATE', 'session_category_created');
  117. define('LOG_SESSION_CATEGORY_DELETE', 'session_category_deleted');
  118. define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
  119. define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
  120. define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
  121. define('LOG_PROMOTION_CREATE', 'promotion_created');
  122. define('LOG_PROMOTION_DELETE', 'promotion_deleted');
  123. define('LOG_CAREER_CREATE', 'career_created');
  124. define('LOG_CAREER_DELETE', 'career_deleted');
  125. // event logs data types
  126. define('LOG_COURSE_CODE', 'course_code');
  127. define('LOG_USER_ID', 'user_id');
  128. define('LOG_USER_OBJECT', 'user_object');
  129. define('LOG_SESSION_ID', 'session_id');
  130. define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
  131. define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
  132. define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
  133. define('LOG_CAREER_ID', 'career_id');
  134. define('LOG_PROMOTION_ID', 'promotion_id');
  135. // Specification for usernames:
  136. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  137. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  138. define('USERNAME_MAX_LENGTH', 40);
  139. define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
  140. //used when login_is_email setting is true
  141. define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
  142. define('USERNAME_PURIFIER_SHALLOW', '/\s/');
  143. // Constants for detection some important PHP5 subversions.
  144. $php_version = (float) PHP_VERSION;
  145. define('IS_PHP_52', !((float)$php_version < 5.2));
  146. define('IS_PHP_53', !((float)$php_version < 5.3));
  147. define('IS_PHP_SUP_OR_EQ_53', ($php_version >= 5.3));
  148. define('IS_PHP_SUP_OR_EQ_52', ($php_version >= 5.2 && !IS_PHP_53));
  149. define('IS_PHP_SUP_OR_EQ_51', ($php_version >= 5.1 && !IS_PHP_52 && !IS_PHP_53));
  150. // This constant is a result of Windows OS detection, it has a boolean value:
  151. // true whether the server runs on Windows OS, false otherwise.
  152. define('IS_WINDOWS_OS', api_is_windows_os());
  153. // Checks for installed optional php-extensions.
  154. define('INTL_INSTALLED', function_exists('intl_get_error_code')); // intl extension (from PECL), it is installed by default as of PHP 5.3.0
  155. define('ICONV_INSTALLED', function_exists('iconv')); // iconv extension, for PHP5 on Windows it is installed by default.
  156. define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
  157. define('DATE_TIME_INSTALLED', class_exists('DateTime')); // datetime extension, it is moved to the core as of PHP 5.2, see http://www.php.net/datetime
  158. // Patterns for processing paths. // Examples:
  159. define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  160. define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
  161. define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i'); // $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
  162. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  163. define('WEB_PATH', 'WEB_PATH');
  164. define('SYS_PATH', 'SYS_PATH');
  165. define('REL_PATH', 'REL_PATH');
  166. define('WEB_SERVER_ROOT_PATH', 'WEB_SERVER_ROOT_PATH');
  167. define('SYS_SERVER_ROOT_PATH', 'SYS_SERVER_ROOT_PATH');
  168. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  169. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  170. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  171. define('REL_CODE_PATH', 'REL_CODE_PATH');
  172. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  173. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  174. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  175. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  176. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  177. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  178. define('PLUGIN_PATH', 'SYS_PLUGIN_PATH'); // deprecated ?
  179. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  180. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  181. define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
  182. define('INCLUDE_PATH', 'INCLUDE_PATH');
  183. define('LIBRARY_PATH', 'LIBRARY_PATH');
  184. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  185. define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
  186. define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
  187. define('SYS_TEST_PATH', 'SYS_TEST_PATH');
  188. define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
  189. define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
  190. // Constants for requesting path conversion.
  191. define('TO_WEB', 'TO_WEB');
  192. define('TO_SYS', 'TO_SYS');
  193. define('TO_REL', 'TO_REL');
  194. // Paths to regidtered specific resource files (scripts, players, etc.)
  195. define('FLASH_PLAYER_AUDIO', '{FLASH_PLAYER_AUDIO}');
  196. define('FLASH_PLAYER_VIDEO', '{FLASH_PLAYER_VIDEO}');
  197. define('SCRIPT_SWFOBJECT', '{SCRIPT_SWFOBJECT}');
  198. define('SCRIPT_ASCIIMATHML', '{SCRIPT_ASCIIMATHML}');
  199. define('DRAWING_ASCIISVG', '{DRAWING_ASCIISVG}');
  200. // Forcing PclZip library to use a custom temporary folder.
  201. define('PCLZIP_TEMPORARY_DIR', api_get_path(SYS_ARCHIVE_PATH));
  202. // Relations type with Human resources manager
  203. define('COURSE_RELATION_TYPE_RRHH', 1);
  204. define('SESSION_RELATION_TYPE_RRHH', 1);
  205. /**
  206. * Inclusion of internationalization libraries
  207. */
  208. require_once dirname(__FILE__).'/internationalization.lib.php';
  209. /* PATHS & FILES - ROUTINES */
  210. /**
  211. * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
  212. * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
  213. *
  214. * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  215. * @param string $type The requested path type (a defined constant), see the examples.
  216. * @param string $path (optional) A path which type is to be converted. Also, it may be a defined constant for a path.
  217. * This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
  218. * @return string The requested path or the converted path.
  219. *
  220. * A terminology note:
  221. * The defined constants used by this function contain the abbreviations WEB, REL, SYS with the following meaning for types:
  222. * WEB - an absolute URL (we often call it web-path),
  223. * example: http://www.mychamilo.org/chamilo/courses/COURSE01/document/lesson01.html;
  224. *
  225. * REL - represents a semi-absolute URL - a web-path, which is relative to the root web-path of the server, without server's base,
  226. * example: /chamilo/courses/COURSE01/document/lesson01.html;
  227. *
  228. * SYS - represents an absolute path inside the scope of server's file system,
  229. * /var/www/chamilo/courses/COURSE01/document/lesson01.html or
  230. * C:/Inetpub/wwwroot/chamilo/courses/COURSE01/document/lesson01.html.
  231. *
  232. * In some abstract sense we can consider these three path types as absolute.
  233. *
  234. * Notes about the current behaviour model:
  235. * 1. Windows back-slashes are converted to slashes in the result.
  236. * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
  237. * a slash too, so an additional check about presense of leading system server base is implemented. For example, the function is
  238. * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
  239. * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
  240. * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
  241. * It has not been identified as needed yet.
  242. * 4. Also, resolving the meta-symbols "." and ".." withiin paths has not been implemented, it is to be identified as needed.
  243. *
  244. * Example:
  245. * Assume that your server root is /var/www/ , Chamilo is installed in a subfolder chamilo/ and the URL of your campus is http://www.mychamilo.org
  246. * The other configuration paramaters have not been changed.
  247. *
  248. * This is how we can retireve mosth used paths, for common purpose:
  249. * api_get_path(REL_PATH) /chamilo/
  250. * api_get_path(REL_COURSE_PATH) /chamilo/courses/
  251. * api_get_path(REL_CODE_PATH) /chamilo/main/
  252. * api_get_path(SYS_SERVER_ROOT_PATH) /var/www/ - This is the physical folder where the system Chamilo has been placed. It is not always equal to $_SERVER['DOCUMENT_ROOT'].
  253. * api_get_path(SYS_PATH) /var/www/chamilo/
  254. * api_get_path(SYS_ARCHIVE_PATH) /var/www/chamilo/archive/
  255. * api_get_path(SYS_COURSE_PATH) /var/www/chamilo/courses/
  256. * api_get_path(SYS_CODE_PATH) /var/www/chamilo/main/
  257. * api_get_path(INCLUDE_PATH) /var/www/chamilo/main/inc/
  258. * api_get_path(LIBRARY_PATH) /var/www/chamilo/main/inc/lib/
  259. * api_get_path(CONFIGURATION_PATH) /var/www/chamilo/main/inc/conf/
  260. * api_get_path(SYS_LANG_PATH) /var/www/chamilo/main/lang/
  261. * api_get_path(SYS_PLUGIN_PATH) /var/www/chamilo/plugin/
  262. * api_get_path(SYS_TEST_PATH) /var/www/chamilo/tests/
  263. * api_get_path(SYS_TEMPLATE_PATH) /var/www/chamilo/main/template/
  264. *
  265. * api_get_path(WEB_SERVER_ROOT_PATH) http://www.mychamilo.org/
  266. * api_get_path(WEB_PATH) http://www.mychamilo.org/chamilo/
  267. * api_get_path(WEB_COURSE_PATH) http://www.mychamilo.org/chamilo/courses/
  268. * api_get_path(WEB_CODE_PATH) http://www.mychamilo.org/chamilo/main/
  269. * api_get_path(WEB_PLUGIN_PATH) http://www.mychamilo.org/chamilo/plugin/
  270. * api_get_path(WEB_ARCHIVE_PATH) http://www.mychamilo.org/chamilo/archive/
  271. * api_get_path(WEB_IMG_PATH) http://www.mychamilo.org/chamilo/main/img/
  272. * api_get_path(WEB_CSS_PATH) http://www.mychamilo.org/chamilo/main/css/
  273. * api_get_path(WEB_LIBRARY_PATH) http://www.mychamilo.org/chamilo/main/inc/lib/
  274. * api_get_path(WEB_TEMPLATE_PATH) http://www.mychamilo.org/chamilo/main/template/
  275. *
  276. *
  277. * This is how we retrieve paths of "registerd" resource files (scripts, players, etc.):
  278. * api_get_path(TO_WEB, FLASH_PLAYER_AUDIO) http://www.mychamilo.org/chamilo/main/inc/lib/mediaplayer/player.swf
  279. * api_get_path(TO_WEB, FLASH_PLAYER_VIDEO) http://www.mychamilo.org/chamilo/main/inc/lib/mediaplayer/player.swf
  280. * api_get_path(TO_SYS, SCRIPT_SWFOBJECT) /var/www/chamilo/main/inc/lib/swfobject/swfobject.js
  281. * api_get_path(TO_REL, SCRIPT_ASCIIMATHML) /chamilo/main/inc/lib/asciimath/ASCIIMathML.js
  282. * ...
  283. *
  284. * We can convert arbitrary paths, that are not registered (no defined constant).
  285. * For guaranteed result, these paths should point inside the system Chamilo.
  286. * Some random examples:
  287. * api_get_path(TO_WEB, $_SERVER['REQUEST_URI'])
  288. * api_get_path(TO_SYS, $_SERVER['PHP_SELF'])
  289. * api_get_path(TO_REL, __FILE__)
  290. * ...
  291. */
  292. function api_get_path($path_type, $path = null) {
  293. static $paths = array(
  294. WEB_PATH => '',
  295. SYS_PATH => '',
  296. REL_PATH => '',
  297. WEB_SERVER_ROOT_PATH => '',
  298. SYS_SERVER_ROOT_PATH => '',
  299. WEB_COURSE_PATH => '',
  300. SYS_COURSE_PATH => '',
  301. REL_COURSE_PATH => '',
  302. REL_CODE_PATH => '',
  303. WEB_CODE_PATH => '',
  304. SYS_CODE_PATH => '',
  305. SYS_LANG_PATH => 'lang/',
  306. WEB_IMG_PATH => 'img/',
  307. WEB_CSS_PATH => 'css/',
  308. SYS_PLUGIN_PATH => 'plugin/',
  309. WEB_PLUGIN_PATH => 'plugin/',
  310. SYS_ARCHIVE_PATH => 'archive/',
  311. WEB_ARCHIVE_PATH => 'archive/',
  312. INCLUDE_PATH => 'inc/',
  313. LIBRARY_PATH => 'inc/lib/',
  314. CONFIGURATION_PATH => 'inc/conf/',
  315. WEB_LIBRARY_PATH => 'inc/lib/',
  316. WEB_AJAX_PATH => 'inc/ajax/',
  317. SYS_TEST_PATH => 'tests/',
  318. WEB_TEMPLATE_PATH => 'template/',
  319. SYS_TEMPLATE_PATH => 'template/'
  320. );
  321. static $resource_paths = array(
  322. FLASH_PLAYER_AUDIO => 'inc/lib/mediaplayer/player.swf',
  323. FLASH_PLAYER_VIDEO => 'inc/lib/mediaplayer/player.swf',
  324. SCRIPT_SWFOBJECT => 'inc/lib/swfobject/swfobject.js',
  325. SCRIPT_ASCIIMATHML => 'inc/lib/javascript/asciimath/ASCIIMathML.js',
  326. DRAWING_ASCIISVG => 'inc/lib/javascript/asciimath/d.svg'
  327. );
  328. static $is_this_function_initialized;
  329. static $server_base_web; // No trailing slash.
  330. static $server_base_sys; // No trailing slash.
  331. static $root_web;
  332. static $root_sys;
  333. static $root_rel;
  334. static $code_folder;
  335. static $course_folder;
  336. // Always load root_web modifications for multiple url features
  337. global $_configuration;
  338. //default $_configuration['root_web'] configuration
  339. $root_web = $_configuration['root_web'];
  340. // Configuration data for already installed system.
  341. $root_sys = $_configuration['root_sys'];
  342. $load_new_config = false;
  343. // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
  344. if ($path_type == WEB_PATH) {
  345. if (isset($_configuration['access_url']) && $_configuration['access_url'] != 1) {
  346. //we look into the DB the function api_get_access_url
  347. $url_info = api_get_access_url($_configuration['access_url']);
  348. $root_web = $url_info['active'] == 1 ? $url_info['url'] : $_configuration['root_web'];
  349. $load_new_config = true;
  350. }
  351. }
  352. if (!$is_this_function_initialized) {
  353. global $_configuration;
  354. $root_rel = $_configuration['url_append'];
  355. $code_folder = $_configuration['code_append'];
  356. $course_folder = $_configuration['course_folder'];
  357. // Support for the installation process.
  358. // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
  359. // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
  360. if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
  361. if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
  362. $root_rel = substr($requested_page_rel, 0, $pos);
  363. // See http://www.mediawiki.org/wiki/Manual:$wgServer
  364. $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  365. $server_name =
  366. isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
  367. : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
  368. : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
  369. : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
  370. : 'localhost')));
  371. if (isset($_SERVER['SERVER_PORT']) && !strpos($server_name, ':')
  372. && (($server_protocol == 'http'
  373. && $_SERVER['SERVER_PORT'] != 80 ) || ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443 ))) {
  374. $server_name .= ":" . $_SERVER['SERVER_PORT'];
  375. }
  376. $root_web = $server_protocol.'://'.$server_name.$root_rel;
  377. $root_sys = str_replace('\\', '/', realpath(dirname(__FILE__).'/../../../')).'/';
  378. $code_folder = 'main/';
  379. $course_folder = 'courses/';
  380. }
  381. // Here we give up, so we don't touch anything.
  382. }
  383. // Dealing with trailing slashes.
  384. $root_web = api_add_trailing_slash($root_web);
  385. $root_sys = api_add_trailing_slash($root_sys);
  386. $root_rel = api_add_trailing_slash($root_rel);
  387. $code_folder = api_add_trailing_slash($code_folder);
  388. $course_folder = api_add_trailing_slash($course_folder);
  389. // Web server base and system server base.
  390. $server_base_web = preg_replace('@'.$root_rel.'$@', '', $root_web); // No trailing slash.
  391. $server_base_sys = preg_replace('@'.$root_rel.'$@', '', $root_sys); // No trailing slash.
  392. // Initialization of a table taht contains common-purpose paths.
  393. $paths[WEB_PATH] = $root_web;
  394. $paths[SYS_PATH] = $root_sys;
  395. $paths[REL_PATH] = $root_rel;
  396. $paths[WEB_SERVER_ROOT_PATH] = $server_base_web.'/';
  397. $paths[SYS_SERVER_ROOT_PATH] = $server_base_sys.'/';
  398. $paths[WEB_COURSE_PATH] = $root_web.$course_folder;
  399. $paths[SYS_COURSE_PATH] = $root_sys.$course_folder;
  400. $paths[REL_COURSE_PATH] = $root_rel.$course_folder;
  401. $paths[REL_CODE_PATH] = $root_rel.$code_folder;
  402. $paths[WEB_CODE_PATH] = $root_web.$code_folder;
  403. $paths[SYS_CODE_PATH] = $root_sys.$code_folder;
  404. // Now we can switch into api_get_path() "terminology".
  405. $paths[SYS_LANG_PATH] = $paths[SYS_CODE_PATH].$paths[SYS_LANG_PATH];
  406. $paths[SYS_PLUGIN_PATH] = $paths[SYS_PATH].$paths[SYS_PLUGIN_PATH];
  407. $paths[SYS_ARCHIVE_PATH] = $paths[SYS_PATH].$paths[SYS_ARCHIVE_PATH];
  408. $paths[SYS_TEST_PATH] = $paths[SYS_PATH].$paths[SYS_TEST_PATH];
  409. $paths[SYS_TEMPLATE_PATH] = $paths[SYS_CODE_PATH].$paths[SYS_TEMPLATE_PATH];
  410. $paths[WEB_CSS_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_CSS_PATH];
  411. $paths[WEB_IMG_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_IMG_PATH];
  412. $paths[WEB_LIBRARY_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_LIBRARY_PATH];
  413. $paths[WEB_AJAX_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_AJAX_PATH];
  414. $paths[WEB_PLUGIN_PATH] = $paths[WEB_PATH].$paths[WEB_PLUGIN_PATH];
  415. $paths[WEB_ARCHIVE_PATH] = $paths[WEB_PATH].$paths[WEB_ARCHIVE_PATH];
  416. $paths[WEB_TEMPLATE_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_TEMPLATE_PATH];
  417. $paths[INCLUDE_PATH] = $paths[SYS_CODE_PATH].$paths[INCLUDE_PATH];
  418. $paths[LIBRARY_PATH] = $paths[SYS_CODE_PATH].$paths[LIBRARY_PATH];
  419. $paths[CONFIGURATION_PATH] = $paths[SYS_CODE_PATH].$paths[CONFIGURATION_PATH];
  420. $is_this_function_initialized = true;
  421. } else {
  422. if ($load_new_config) {
  423. // Redefining variables to work well with the "multiple url" feature
  424. // All web paths need to be here
  425. $web_paths = array(
  426. WEB_PATH => '',
  427. WEB_SERVER_ROOT_PATH => '',
  428. WEB_COURSE_PATH => '',
  429. WEB_CODE_PATH => '',
  430. WEB_IMG_PATH => 'img/',
  431. WEB_CSS_PATH => 'css/',
  432. WEB_PLUGIN_PATH => 'plugin/',
  433. WEB_ARCHIVE_PATH => 'archive/',
  434. WEB_LIBRARY_PATH => 'inc/lib/',
  435. WEB_AJAX_PATH => 'inc/ajax/',
  436. );
  437. $root_web = api_add_trailing_slash($root_web);
  438. // Web server base and system server base.
  439. $server_base_web = preg_replace('@'.$root_rel.'$@', '', $root_web); // No trailing slash.
  440. // Redefine root webs
  441. $paths[WEB_PATH] = $root_web;
  442. $paths[WEB_SERVER_ROOT_PATH] = $server_base_web.'/';
  443. $paths[WEB_COURSE_PATH] = $root_web.$course_folder;
  444. $paths[WEB_CODE_PATH] = $root_web.$code_folder;
  445. $paths[WEB_IMG_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_IMG_PATH];
  446. $paths[WEB_CSS_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_CSS_PATH];
  447. $paths[WEB_PLUGIN_PATH] = $paths[WEB_PATH].$web_paths[WEB_PLUGIN_PATH];
  448. $paths[WEB_ARCHIVE_PATH] = $paths[WEB_PATH].$web_paths[WEB_ARCHIVE_PATH];
  449. $paths[WEB_LIBRARY_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_LIBRARY_PATH];
  450. $paths[WEB_AJAX_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_AJAX_PATH];
  451. }
  452. }
  453. // Shallow purification and validation of input parameters.
  454. $path_type = trim($path_type);
  455. $path = trim($path);
  456. if (empty($path_type)) {
  457. return null;
  458. }
  459. // Retrieving a common-purpose path.
  460. if (isset($paths[$path_type])) {
  461. return $paths[$path_type];
  462. }
  463. // Retrieving a specific resource path.
  464. if (isset($resource_paths[$path])) {
  465. switch ($path_type) {
  466. case TO_WEB:
  467. return $paths[WEB_CODE_PATH].$resource_paths[$path];
  468. case TO_SYS:
  469. return $paths[SYS_CODE_PATH].$resource_paths[$path];
  470. case TO_REL:
  471. return $paths[REL_CODE_PATH].$resource_paths[$path];
  472. default:
  473. return null;
  474. }
  475. }
  476. // Common-purpose paths as a second parameter - recognition.
  477. if (isset($paths[$path])) {
  478. $path = $paths[$path];
  479. }
  480. // Second purification.
  481. // Replacing Windows back slashes.
  482. $path = str_replace('\\', '/', $path);
  483. // Query strings sometimes mighth wrongly appear in non-URLs.
  484. // Let us check remove them from all types of paths.
  485. if (($pos = strpos($path, '?')) !== false) {
  486. $path = substr($path, 0, $pos);
  487. }
  488. // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
  489. if (preg_match(VALID_WEB_PATH, $path)) {
  490. // A special case: When a URL points to the document download script directly, without
  491. // mod-rewrite translation, we have to translate it into an "ordinary" web path.
  492. // For example:
  493. // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
  494. // becomes
  495. // http://localhost/chamilo/courses/TEST/document/image.png
  496. // TEST is a course directory name, so called "system course code".
  497. if (strpos($path, 'download.php') !== false) { // Fast detection first.
  498. $path = urldecode($path);
  499. if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
  500. $sys_course_code =
  501. isset($_SESSION['_course']['sysCode']) // User is inside a course?
  502. ? $_SESSION['_course']['sysCode'] // Yes, then use course's directory name.
  503. : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
  504. $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
  505. }
  506. }
  507. // Replacement of the present web server base with a slash '/'.
  508. $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
  509. } elseif (strpos($path, $server_base_sys) === 0) {
  510. $path = preg_replace('@^'.$server_base_sys.'@', '', $path);
  511. } elseif (strpos($path, '/') === 0) {
  512. // Leading slash - we assume that this path is semi-absolute (REL),
  513. // then path is left without furthes modifications.
  514. } else {
  515. return null; // Probably implementation of this case won't be needed.
  516. }
  517. // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
  518. $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  519. // Path conversion to the requested type.
  520. switch ($path_type) {
  521. case TO_WEB:
  522. return $server_base_web.$path;
  523. case TO_SYS:
  524. return $server_base_sys.$path;
  525. case TO_REL:
  526. return $path;
  527. }
  528. return null;
  529. }
  530. /**
  531. * This function checks whether a given path points inside the system.
  532. * @param string $path The path to be tesed. It should be full path, web-absolute (WEB), semi-absolute (REL) or system-absolyte (SYS).
  533. * @return bool Returns true when the given path is inside the system, false otherwise.
  534. */
  535. function api_is_internal_path($path) {
  536. $path = str_replace('\\', '/', trim($path));
  537. if (empty($path)) {
  538. return false;
  539. }
  540. if (strpos($path, api_remove_trailing_slash(api_get_path(WEB_PATH))) === 0) {
  541. return true;
  542. }
  543. if (strpos($path, api_remove_trailing_slash(api_get_path(SYS_PATH))) === 0) {
  544. return true;
  545. }
  546. $server_base_web = api_remove_trailing_slash(api_get_path(REL_PATH));
  547. $server_base_web = empty($server_base_web) ? '/' : $server_base_web;
  548. if (strpos($path, $server_base_web) === 0) {
  549. return true;
  550. }
  551. return false;
  552. }
  553. /**
  554. * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
  555. * @param string $path The input path.
  556. * @return string Returns the modified path.
  557. */
  558. function api_add_trailing_slash($path) {
  559. return substr($path, -1) == '/' ? $path : $path.'/';
  560. }
  561. /**
  562. * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
  563. * @param string $path The input path.
  564. * @return string Returns the modified path.
  565. */
  566. function api_remove_trailing_slash($path) {
  567. return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
  568. }
  569. /**
  570. * Checks the RFC 3986 syntax of a given URL.
  571. * @param string $url The URL to be checked.
  572. * @param bool $absolute Whether the URL is absolute (beginning with a scheme such as "http:").
  573. * @return bool Returns the URL if it is valid, FALSE otherwise.
  574. * This function is an adaptation from the function valid_url(), Drupal CMS.
  575. * @link http://drupal.org
  576. * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
  577. * @link http://bugs.php.net/51192
  578. */
  579. function api_valid_url($url, $absolute = false) {
  580. if ($absolute) {
  581. if (preg_match("
  582. /^ # Start at the beginning of the text
  583. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  584. (?: # Userinfo (optional) which is typically
  585. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  586. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  587. )?
  588. (?:
  589. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  590. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  591. )
  592. (?::[0-9]+)? # Server port number (optional)
  593. (?:[\/|\?]
  594. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  595. *)?
  596. $/xi", $url)) {
  597. return $url;
  598. }
  599. return false;
  600. } else {
  601. return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
  602. }
  603. }
  604. /**
  605. * Checks whether a given string looks roughly like an email address.
  606. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator.
  607. * Conforms approximately to RFC2822
  608. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  609. * This function is an adaptation from the method PHPMailer::ValidateAddress(), PHPMailer module.
  610. * @link http://phpmailer.worxware.com
  611. * @param string $address The e-mail address to be checked.
  612. * @return mixed Returns the e-mail if it is valid, FALSE otherwise.
  613. */
  614. function api_valid_email($address) {
  615. // disable for now because the results are incoherent - YW 20110926
  616. if (function_exists('filter_var')) { // Introduced in PHP 5.2.
  617. return filter_var($address, FILTER_VALIDATE_EMAIL);
  618. } else {
  619. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address) ? $address : false;
  620. }
  621. }
  622. /* PROTECTION FUNCTIONS
  623. Use these functions to protect your scripts. */
  624. /**
  625. * Function used to protect a course script.
  626. * The function blocks access when
  627. * - there is no $_SESSION["_course"] defined; or
  628. * - $is_allowed_in_course is set to false (this depends on the course
  629. * visibility and user status).
  630. *
  631. * This is only the first proposal, test and improve!
  632. * @param boolean Option to print headers when displaying error message. Default: false
  633. * @return boolean True if the user has access to the current course or is out of a course context, false otherwise
  634. * @todo replace global variable
  635. * @author Roan Embrechts
  636. */
  637. function api_protect_course_script($print_headers = false) {
  638. global $is_allowed_in_course;
  639. $is_visible = false;
  640. if (api_is_platform_admin()) {
  641. return true;
  642. }
  643. $course_info = api_get_course_info();
  644. if (isset($course_info) && !empty($course_info['visibility'])) {
  645. switch($course_info['visibility']) {
  646. default:
  647. case 0: //Completely closed: the course is only accessible to the teachers.
  648. if (api_get_user_id() && !api_is_anonymous() && (api_is_allowed_to_edit())) {
  649. $is_visible = true;
  650. }
  651. break;
  652. case 1: //Private - access authorized to course members only
  653. if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
  654. $is_visible = true;
  655. }
  656. break;
  657. case 2: // Open - access allowed for users registered on the platform
  658. if (api_get_user_id() && !api_is_anonymous()) {
  659. $is_visible = true;
  660. }
  661. break;
  662. case 3: //Open - access allowed for the whole world
  663. $is_visible = true;
  664. break;
  665. }
  666. }
  667. if (!$is_visible) {
  668. api_not_allowed($print_headers);
  669. return false;
  670. }
  671. return true;
  672. }
  673. /**
  674. * Function used to protect an admin script.
  675. * The function blocks access when the user has no platform admin rights.
  676. * This is only the first proposal, test and improve!
  677. *
  678. * @author Roan Embrechts
  679. */
  680. function api_protect_admin_script($allow_sessions_admins = false) {
  681. if (!api_is_platform_admin($allow_sessions_admins)) {
  682. api_not_allowed(true);
  683. return false;
  684. }
  685. return true;
  686. }
  687. /**
  688. * Function used to prevent anonymous users from accessing a script.
  689. *
  690. * @author Roan Embrechts
  691. */
  692. function api_block_anonymous_users($print_headers = true) {
  693. global $_user;
  694. if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) {
  695. api_not_allowed($print_headers);
  696. return false;
  697. }
  698. return true;
  699. }
  700. /* ACCESSOR FUNCTIONS
  701. Don't access kernel variables directly, use these functions instead. */
  702. /**
  703. * @return an array with the navigator name and version
  704. */
  705. function api_get_navigator() {
  706. $navigator = 'Unknown';
  707. $version = 0;
  708. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
  709. $navigator = 'Opera';
  710. list (, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  711. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  712. $navigator = 'Internet Explorer';
  713. list (, $version) = explode('MSIE', $_SERVER['HTTP_USER_AGENT']);
  714. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
  715. $navigator = 'Chrome';
  716. list (, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
  717. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
  718. $navigator = 'Mozilla';
  719. list (, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  720. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
  721. $navigator = 'Netscape';
  722. list (, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  723. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
  724. $navigator = 'Konqueror';
  725. list (, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
  726. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
  727. $navigator = 'AppleWebKit';
  728. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  729. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) {
  730. $navigator = 'Safari';
  731. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  732. }
  733. $version = str_replace('/', '', $version);
  734. if (strpos($version, '.') === false) {
  735. $version = number_format(doubleval($version), 1);
  736. }
  737. $return_array = array ('name' => $navigator, 'version' => $version);
  738. return $return_array;
  739. }
  740. /**
  741. * @return True if user selfregistration is allowed, false otherwise.
  742. */
  743. function api_is_self_registration_allowed() {
  744. return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
  745. }
  746. /**
  747. * This function returns the id of the user which is stored in the $_user array.
  748. *
  749. * example: The function can be used to check if a user is logged in
  750. * if (api_get_user_id())
  751. * @return integer the id of the current user, 0 if is empty
  752. */
  753. function api_get_user_id() {
  754. return empty($GLOBALS['_user']['user_id']) ? 0 : intval($GLOBALS['_user']['user_id']);
  755. }
  756. /**
  757. * Gets the list of courses a specific user is subscribed to
  758. * @param int User ID
  759. * @param boolean Whether to get session courses or not - NOT YET IMPLEMENTED
  760. * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
  761. */
  762. function api_get_user_courses($userid, $fetch_session = true) {
  763. if ($userid != strval(intval($userid))) { return array(); } //get out if not integer
  764. $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
  765. $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  766. $t_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  767. $t_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  768. $t_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  769. $sql_select_courses = "SELECT cc.code code, cc.db_name db, cc.directory dir, cu.status status
  770. FROM $t_course cc,
  771. $t_course_user cu
  772. WHERE cc.code = cu.course_code
  773. AND cu.user_id = '".$userid."' AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
  774. $result = Database::query($sql_select_courses);
  775. if ($result === false) { return array(); }
  776. while ($row = Database::fetch_array($result)) {
  777. // we only need the database name of the course
  778. $courses[] = $row;
  779. }
  780. return $courses;
  781. }
  782. /**
  783. * Formats user information into a standard array
  784. *
  785. * @param array Non-standard user array
  786. * @return array Standard user array
  787. */
  788. function _api_format_user($user) {
  789. $result = array();
  790. if (isset($user['firstname']) && isset($user['lastname'])) {
  791. $firstname = $user['firstname'];
  792. $lastname = $user['lastname'];
  793. } elseif (isset($user['firstName']) && isset($user['lastName'])) {
  794. $firstname = $user['firstName'];
  795. $lastname = $user['lastName'];
  796. }
  797. $result['complete_name'] = api_get_person_name($firstname, $lastname);
  798. $result['firstname'] = $firstname;
  799. $result['lastname'] = $lastname;
  800. // Kept for historical reasons
  801. $result['firstName'] = $firstname;
  802. $result['lastName'] = $lastname;
  803. if (isset($user['email'])) {
  804. $result['mail'] = $user['email'];
  805. } else {
  806. $result['mail'] = $user['mail'];
  807. }
  808. $user_id = intval($user['user_id']);
  809. $result['picture_uri'] = $user['picture_uri'];
  810. $result['user_id'] = $user_id;
  811. $result['official_code'] = $user['official_code'];
  812. $result['status'] = $user['status'];
  813. $result['auth_source'] = $user['auth_source'];
  814. if (isset($user['username'])) {
  815. $result['username'] = $user['username'];
  816. }
  817. $result['theme'] = $user['theme'];
  818. $result['language'] = $user['language'];
  819. if (!isset($user['lastLogin']) && !isset($user['last_login'])) {
  820. require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
  821. $timestamp = Tracking::get_last_connection_date($result['user_id'], false, true);
  822. // Convert the timestamp back into a datetime
  823. // NOTE: this timestamp has ALREADY been converted to the local timezone in the get_last_connection_date function
  824. $last_login = date('Y-m-d H:i:s', $timestamp);
  825. } else {
  826. if (isset($user['lastLogin'])) {
  827. $last_login = $user['lastLogin'];
  828. } else {
  829. $last_login = $user['last_login'];
  830. }
  831. }
  832. $result['last_login'] = $last_login;
  833. // Kept for historical reasons
  834. $result['lastLogin'] = $last_login;
  835. //Getting user avatar
  836. $picture_filename = trim($user['picture_uri']);
  837. $avatar = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  838. $avatar_small = api_get_path(WEB_CODE_PATH).'img/unknown_22.jpg';
  839. $dir = 'upload/users/'.$user_id.'/';
  840. if (!empty($picture_filename) && api_is_anonymous() ) {
  841. if (api_get_setting('split_users_upload_directory') === 'true') {
  842. $dir = 'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
  843. }
  844. }
  845. $image_sys_path = api_get_path(SYS_CODE_PATH).$dir.$picture_filename;
  846. if (file_exists($image_sys_path) && !is_dir($image_sys_path)) {
  847. $avatar = api_get_path(WEB_CODE_PATH).$dir.$picture_filename;
  848. $avatar_small = api_get_path(WEB_CODE_PATH).$dir.'small_'.$picture_filename;
  849. }
  850. $result['avatar'] = $avatar;
  851. $result['avatar_small'] = $avatar_small;
  852. if (isset($user['user_is_online'])) {
  853. $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
  854. }
  855. if (isset($user['user_is_online_in_chat'])) {
  856. $result['user_is_online_in_chat'] = intval($user['user_is_online_in_chat']);
  857. }
  858. return $result;
  859. }
  860. /**
  861. * Finds all the information about a user. If no paramater is passed you find all the information about the current user.
  862. * @param $user_id (integer): the id of the user
  863. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  864. * @author Patrick Cool <patrick.cool@UGent.be>
  865. * @version 21 September 2004
  866. */
  867. function api_get_user_info($user_id = '', $check_if_user_is_online = false) {
  868. if ($user_id == '') {
  869. return _api_format_user($GLOBALS['_user']);
  870. }
  871. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".Database::escape_string($user_id)."'";
  872. $result = Database::query($sql);
  873. if (Database::num_rows($result) > 0) {
  874. $result_array = Database::fetch_array($result);
  875. if ($check_if_user_is_online) {
  876. $use_status_in_platform = user_is_online($user_id);
  877. $result_array['user_is_online'] = $use_status_in_platform;
  878. $user_online_in_chat = 0;
  879. if ($use_status_in_platform) {
  880. $user_status = UserManager::get_extra_user_data_by_field($user_id, 'user_chat_status', false, true);
  881. if (intval($user_status['user_chat_status']) == 1) {
  882. $user_online_in_chat = 1;
  883. }
  884. }
  885. $result_array['user_is_online_in_chat'] = $user_online_in_chat;
  886. }
  887. $user = _api_format_user($result_array);
  888. return $user;
  889. }
  890. return false;
  891. }
  892. /**
  893. * Finds all the information about a user from username instead of user id
  894. * @param $username (string): the username
  895. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  896. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  897. */
  898. function api_get_user_info_from_username($username = '') {
  899. if (empty($username)) { return false; }
  900. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE username='".Database::escape_string($username)."'";
  901. $result = Database::query($sql);
  902. if (Database::num_rows($result) > 0) {
  903. $result_array = Database::fetch_array($result);
  904. return _api_format_user($result_array);
  905. }
  906. return false;
  907. }
  908. /**
  909. * @TODO This function should be the real id (integer)
  910. * Returns the current course code (string)
  911. */
  912. function api_get_course_id() {
  913. return $GLOBALS['_cid'];
  914. }
  915. /**
  916. * Returns the current course id (integer)
  917. */
  918. function api_get_real_course_id() {
  919. return isset($_SESSION['_real_cid']) ? intval($_SESSION['_real_cid']) : 0;
  920. }
  921. /**
  922. * Returns the current course id (integer)
  923. */
  924. function api_get_course_int_id() {
  925. return isset($_SESSION['_real_cid']) ? intval($_SESSION['_real_cid']) : 0;
  926. }
  927. /**
  928. * Returns the current course directory
  929. *
  930. * This function relies on api_get_course_info()
  931. * @param string The course code - optional (takes it from session if not given)
  932. * @return string The directory where the course is located inside the Chamilo "courses" directory
  933. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  934. */
  935. function api_get_course_path($course_code = null) {
  936. $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
  937. return $info['path'];
  938. }
  939. /**
  940. * Gets a course setting from the current course_setting table. Try always using integer values.
  941. * @param string The name of the setting we want from the table
  942. * @param string Optional: course code
  943. * @return mixed The value of that setting in that table. Return -1 if not found.
  944. */
  945. function api_get_course_setting($setting_name, $course_code = null) {
  946. $course_info = api_get_course_info($course_code);
  947. $table = Database::get_course_table(TABLE_COURSE_SETTING);
  948. $setting_name = Database::escape_string($setting_name);
  949. if (!empty($course_info['real_id']) && !empty($setting_name)) {
  950. $sql = "SELECT value FROM $table WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
  951. $res = Database::query($sql);
  952. if (Database::num_rows($res) > 0) {
  953. $row = Database::fetch_array($res);
  954. return $row['value'];
  955. }
  956. }
  957. return -1;
  958. }
  959. /**
  960. * Gets an anonymous user ID
  961. *
  962. * For some tools that need tracking, like the learnpath tool, it is necessary
  963. * to have a usable user-id to enable some kind of tracking, even if not
  964. * perfect. An anonymous ID is taken from the users table by looking for a
  965. * status of "6" (anonymous).
  966. * @return int User ID of the anonymous user, or O if no anonymous user found
  967. */
  968. function api_get_anonymous_id() {
  969. $table = Database::get_main_table(TABLE_MAIN_USER);
  970. $sql = "SELECT user_id FROM $table WHERE status = 6";
  971. $res = Database::query($sql);
  972. if (Database::num_rows($res) > 0) {
  973. $row = Database::fetch_array($res);
  974. //error_log('api_get_anonymous_id() returns '.$row['user_id'], 0);
  975. return $row['user_id'];
  976. }
  977. // No anonymous user was found.
  978. return 0;
  979. }
  980. /**
  981. * Returns the cidreq parameter name + current course id taken from
  982. * $GLOBALS['_cid'] and returns a string like 'cidReq=ABC&id_session=123
  983. * @return string Course & session references to add to a URL
  984. */
  985. function api_get_cidreq() {
  986. return empty($GLOBALS['_cid']) ? '' : 'cidReq='.htmlspecialchars($GLOBALS['_cid']).
  987. (api_get_session_id() == 0 ? '&amp;id_session=0' : '&amp;id_session='.api_get_session_id()).
  988. (api_get_group_id() == 0 ? '&amp;gidReq=0' : '&amp;gidReq='.api_get_group_id());
  989. }
  990. /**
  991. * Returns the current course info array.
  992. * Note: this array is only defined if the user is inside a course.
  993. * Array elements:
  994. * ['name']
  995. * ['official_code']
  996. * ['sysCode']
  997. * ['path']
  998. * ['dbName']
  999. * ['dbNameGlu']
  1000. * ['titular']
  1001. * ['language']
  1002. * ['extLink']['url' ]
  1003. * ['extLink']['name']
  1004. * ['categoryCode']
  1005. * ['categoryName']
  1006. *
  1007. * Now if the course_code is given, the returned array gives info about that
  1008. * particular course, not specially the current one.
  1009. * @todo Same behaviour as api_get_user_info so that api_get_course_id becomes absolete too.
  1010. */
  1011. function api_get_course_info($course_code = null) {
  1012. if (!empty($course_code)) {
  1013. $course_code = Database::escape_string($course_code);
  1014. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1015. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1016. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  1017. FROM $course_table
  1018. LEFT JOIN $course_cat_table
  1019. ON course.category_code = course_category.code
  1020. WHERE course.code = '$course_code'";
  1021. $result = Database::query($sql);
  1022. $_course = array();
  1023. if (Database::num_rows($result) > 0) {
  1024. global $_configuration;
  1025. $course_data = Database::fetch_array($result);
  1026. $_course['id' ] = $course_data['code' ];
  1027. $_course['code' ] = $course_data['code' ];
  1028. $_course['name' ] = $course_data['title' ];
  1029. $_course['title' ] = $course_data['title' ];
  1030. $_course['official_code'] = $course_data['visual_code' ]; // Use in echo statements.
  1031. $_course['sysCode' ] = $course_data['code' ]; // Use as key in db.
  1032. $_course['path' ] = $course_data['directory' ]; // Use as key in path.
  1033. $_course['directory' ] = $course_data['directory' ];
  1034. //@todo should be deprecated
  1035. $_course['dbName' ] = $course_data['db_name' ]; // Use as key in db list.
  1036. $_course['db_name' ] = $course_data['db_name']; //
  1037. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // Use in all queries.
  1038. $_course['titular' ] = $course_data['tutor_name' ];
  1039. $_course['language' ] = $course_data['course_language'];
  1040. $_course['extLink' ]['url' ] = $course_data['department_url' ];
  1041. $_course['extLink' ]['name'] = $course_data['department_name'];
  1042. $_course['categoryCode' ] = $course_data['faCode' ];
  1043. $_course['categoryName' ] = $course_data['faName' ];
  1044. $_course['visibility' ] = $course_data['visibility' ];
  1045. $_course['subscribe_allowed'] = $course_data['subscribe' ];
  1046. $_course['unubscribe_allowed'] = $course_data['unsubscribe' ];
  1047. $_course['department_name'] = $course_data['department_name'];
  1048. $_course['department_url'] = $course_data['department_url' ];
  1049. $_course['legal_agreement'] = $course_data['legal_agreement' ];
  1050. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  1051. // The real_id is an integer. It is mandatory for future implementations.
  1052. $_course['real_id' ] = $course_data['id' ];
  1053. $_course['activate_legal'] = $course_data['activate_legal'];
  1054. //I know this is bad, but this reflects that it was a bad decistion to not add a flag in the DB if an image exists
  1055. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png')) {
  1056. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png';
  1057. } else {
  1058. $url_image = api_get_path(WEB_IMG_PATH).'without_picture.png';
  1059. }
  1060. $_course['course_image'] = $url_image;
  1061. }
  1062. return $_course;
  1063. }
  1064. global $_course;
  1065. if ($_course == '-1') $_course = array();
  1066. return $_course;
  1067. }
  1068. /**
  1069. * Returns the current course info array.
  1070. * Now if the course_code is given, the returned array gives info about that
  1071. * particular course, not specially the current one.
  1072. */
  1073. function api_get_course_info_by_id($id = null) {
  1074. if (!empty($id)) {
  1075. $id = intval($id);
  1076. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1077. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1078. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  1079. FROM $course_table
  1080. LEFT JOIN $course_cat_table
  1081. ON course.category_code = course_category.code
  1082. WHERE course.id = $id";
  1083. $result = Database::query($sql);
  1084. $_course = array();
  1085. if (Database::num_rows($result) > 0) {
  1086. global $_configuration;
  1087. $course_data = Database::fetch_array($result);
  1088. $_course['id' ] = $course_data['code' ];
  1089. // Added
  1090. $_course['code' ] = $course_data['code' ];
  1091. $_course['name' ] = $course_data['title' ];
  1092. $_course['title' ] = $course_data['title' ];
  1093. $_course['official_code'] = $course_data['visual_code' ]; // Use in echo statements.
  1094. $_course['sysCode' ] = $course_data['code' ]; // Use as key in db.
  1095. $_course['path' ] = $course_data['directory' ]; // Use as key in path.
  1096. $_course['directory' ] = $course_data['directory' ];
  1097. //@todo should be deprecated
  1098. $_course['dbName' ] = $course_data['db_name' ]; // Use as key in db list.
  1099. $_course['db_name' ] = $course_data['db_name' ];
  1100. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // Use in all queries.
  1101. $_course['titular' ] = $course_data['tutor_name' ];
  1102. $_course['language' ] = $course_data['course_language'];
  1103. $_course['extLink' ]['url' ] = $course_data['department_url' ];
  1104. $_course['extLink' ]['name'] = $course_data['department_name'];
  1105. $_course['categoryCode' ] = $course_data['faCode' ];
  1106. $_course['categoryName' ] = $course_data['faName' ];
  1107. $_course['visibility' ] = $course_data['visibility' ];
  1108. $_course['subscribe_allowed'] = $course_data['subscribe' ];
  1109. $_course['unubscribe_allowed'] = $course_data['unsubscribe' ];
  1110. $_course['real_id' ] = $course_data['id' ];
  1111. $_course['title' ] = $course_data['title' ];
  1112. $_course['course_language'] = $course_data['course_language'];
  1113. $_course['activate_legal'] = $course_data['activate_legal'];
  1114. $_course['legal_agreement'] = $course_data['legal_agreement'];
  1115. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  1116. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png')) {
  1117. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png';
  1118. } else {
  1119. $url_image = api_get_path(WEB_IMG_PATH).'without_picture.png';
  1120. }
  1121. $_course['course_image'] = $url_image;
  1122. }
  1123. return $_course;
  1124. }
  1125. //global $_course;
  1126. global $_course;
  1127. if ($_course == '-1') $_course = array();
  1128. return $_course;
  1129. }
  1130. /* SESSION MANAGEMENT */
  1131. /**
  1132. * Starts the Chamilo session.
  1133. *
  1134. * The default lifetime for session is set here. It is not possible to have it
  1135. * as a database setting as it is used before the database connection has been made.
  1136. * It is taken from the configuration file, and if it doesn't exist there, it is set
  1137. * to 360000 seconds
  1138. *
  1139. * @author Olivier Brouckaert
  1140. * @param string variable - the variable name to save into the session
  1141. */
  1142. function api_session_start($already_installed = true) {
  1143. global $_configuration;
  1144. /* Causes too many problems and is not configurable dynamically.
  1145. if ($already_installed) {
  1146. $session_lifetime = 360000;
  1147. if (isset($_configuration['session_lifetime'])) {
  1148. $session_lifetime = $_configuration['session_lifetime'];
  1149. }
  1150. //session_set_cookie_params($session_lifetime,api_get_path(REL_PATH));
  1151. }
  1152. */
  1153. if (!isset($_configuration['session_stored_in_db'])) {
  1154. $_configuration['session_stored_in_db'] = false;
  1155. }
  1156. if ($_configuration['session_stored_in_db'] && function_exists('session_set_save_handler')) {
  1157. require_once api_get_path(LIBRARY_PATH).'session_handler.class.php';
  1158. $session_handler = new session_handler();
  1159. @session_set_save_handler(array(& $session_handler, 'open'), array(& $session_handler, 'close'), array(& $session_handler, 'read'), array(& $session_handler, 'write'), array(& $session_handler, 'destroy'), array(& $session_handler, 'garbage'));
  1160. }
  1161. /*
  1162. * Prevent Session fixation bug fixes
  1163. * See http://support.chamilo.org/issues/3600
  1164. * http://php.net/manual/en/session.configuration.php
  1165. * @todo use session_set_cookie_params with some custom admin parameters
  1166. */
  1167. //session.cookie_lifetime
  1168. //the session ID is only accepted from a cookie
  1169. ini_set('session.use_only_cookies', 1);
  1170. //HTTPS only if possible
  1171. //ini_set('session.cookie_secure', 1);
  1172. //session ID in the cookie is only readable by the server
  1173. ini_set('session.cookie_httponly', 1);
  1174. //Use entropy file
  1175. //session.entropy_file
  1176. //ini_set('session.entropy_length', 128);
  1177. //Do not include the identifier in the URL, and not to read the URL for identifiers.
  1178. ini_set('session.use_trans_sid', 0);
  1179. session_name('ch_sid');
  1180. session_start();
  1181. if (!isset($_SESSION['starttime'])) {
  1182. $_SESSION['starttime'] = time();
  1183. }
  1184. if ($already_installed) {
  1185. if (empty($_SESSION['checkDokeosURL'])) {
  1186. $_SESSION['checkDokeosURL'] = api_get_path(WEB_PATH);
  1187. //$_SESSION['session_expiry'] = time() + $session_lifetime; // It is useless at the moment.
  1188. } elseif ($_SESSION['checkDokeosURL'] != api_get_path(WEB_PATH)) {
  1189. api_session_clear();
  1190. //$_SESSION['session_expiry'] = time() + $session_lifetime;
  1191. }
  1192. }
  1193. if ( isset($_SESSION['starttime']) && $_SESSION['starttime'] < time() - $_configuration['session_lifetime'] ) {
  1194. $_SESSION['starttime'] = time();
  1195. }
  1196. }
  1197. /**
  1198. * Saves a variable into the session
  1199. *
  1200. * BUG: function works only with global variables
  1201. *
  1202. * @author Olivier Brouckaert
  1203. * @param string variable - the variable name to save into the session
  1204. */
  1205. function api_session_register($variable) {
  1206. global $$variable;
  1207. $_SESSION[$variable] = $$variable;
  1208. }
  1209. /**
  1210. * Removes a variable from the session.
  1211. *
  1212. * @author Olivier Brouckaert
  1213. * @param string variable - the variable name to remove from the session
  1214. */
  1215. function api_session_unregister($variable) {
  1216. $variable = strval($variable);
  1217. if (isset($GLOBALS[$variable])) {
  1218. unset ($GLOBALS[$variable]);
  1219. }
  1220. if (isset($_SESSION[$variable])) {
  1221. unset($_SESSION[$variable]);
  1222. }
  1223. }
  1224. /**
  1225. * Clears the session
  1226. *
  1227. * @author Olivier Brouckaert
  1228. */
  1229. function api_session_clear() {
  1230. session_regenerate_id();
  1231. session_unset();
  1232. $_SESSION = array();
  1233. }
  1234. /**
  1235. * Destroys the session
  1236. *
  1237. * @author Olivier Brouckaert
  1238. */
  1239. function api_session_destroy() {
  1240. session_unset();
  1241. $_SESSION = array();
  1242. session_destroy();
  1243. }
  1244. /* STRING MANAGEMENT */
  1245. /**
  1246. * Add a parameter to the existing URL. If this parameter already exists,
  1247. * just replace it with the new value
  1248. * @param string The URL
  1249. * @param string param=value string
  1250. * @param boolean Whether to filter XSS or not
  1251. * @return string The URL with the added parameter
  1252. */
  1253. function api_add_url_param($url, $param, $filter_xss = true) {
  1254. if (empty($param)) {
  1255. return $url;
  1256. }
  1257. if (strpos($url, '?') !== false) {
  1258. if ($param[0] != '&') {
  1259. $param = '&'.$param;
  1260. }
  1261. list (, $query_string) = explode('?', $url);
  1262. $param_list1 = explode('&', $param);
  1263. $param_list2 = explode('&', $query_string);
  1264. $param_list1_keys = $param_list1_vals = array();
  1265. foreach ($param_list1 as $key => $enreg) {
  1266. list ($param_list1_keys[$key], $param_list1_vals[$key]) = explode('=', $enreg);
  1267. }
  1268. $param_list1 = array ('keys' => $param_list1_keys, 'vals' => $param_list1_vals);
  1269. foreach ($param_list2 as $enreg) {
  1270. $enreg = explode('=', $enreg);
  1271. $key = array_search($enreg[0], $param_list1['keys']);
  1272. if (!is_null($key) && !is_bool($key)) {
  1273. $url = str_replace($enreg[0].'='.$enreg[1], $enreg[0].'='.$param_list1['vals'][$key], $url);
  1274. $param = str_replace('&'.$enreg[0].'='.$param_list1['vals'][$key], '', $param);
  1275. }
  1276. }
  1277. $url .= $param;
  1278. } else {
  1279. $url = $url.'?'.$param;
  1280. }
  1281. if ($filter_xss === true) {
  1282. $url = Security::remove_XSS(urldecode($url));
  1283. }
  1284. return $url;
  1285. }
  1286. /**
  1287. * Returns a difficult to guess password.
  1288. * @param int $length, the length of the password
  1289. * @return string the generated password
  1290. */
  1291. function api_generate_password($length = 8) {
  1292. $characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  1293. if ($length < 2) {
  1294. $length = 2;
  1295. }
  1296. $password = '';
  1297. for ($i = 0; $i < $length; $i ++) {
  1298. $password .= $characters[rand() % strlen($characters)];
  1299. }
  1300. return $password;
  1301. }
  1302. /**
  1303. * Checks a password to see wether it is OK to use.
  1304. * @param string $password
  1305. * @return true if the password is acceptable, false otherwise
  1306. * Notes about what a password "OK to use" is:
  1307. * 1. The password should be at least 5 characters long.
  1308. * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
  1309. * 3. The password should contain at least 3 letters.
  1310. * 4. It should contain at least 2 digits.
  1311. * 5. It should not contain 3 or more consequent (according to ASCII table) characters.
  1312. */
  1313. function api_check_password($password) {
  1314. $password_length = api_strlen($password);
  1315. if ($password_length < 5) {
  1316. return false;
  1317. }
  1318. $password = api_strtolower($password);
  1319. $letters = 0;
  1320. $digits = 0;
  1321. $consequent_characters = 0;
  1322. $previous_character_code = 0;
  1323. for ($i = 0; $i < $password_length; $i ++) {
  1324. $current_character_code = api_ord(api_substr($password, $i, 1));
  1325. if ($i && abs($current_character_code - $previous_character_code) <= 1) {
  1326. $consequent_characters ++;
  1327. if ($consequent_characters == 3) {
  1328. return false;
  1329. }
  1330. } else {
  1331. $consequent_characters = 1;
  1332. }
  1333. if ($current_character_code >= 97 && $current_character_code <= 122) {
  1334. $letters ++;
  1335. } elseif ($current_character_code >= 48 && $current_character_code <= 57) {
  1336. $digits ++;
  1337. } else {
  1338. return false;
  1339. }
  1340. $previous_character_code = $current_character_code;
  1341. }
  1342. return ($letters >= 3 && $digits >= 2);
  1343. }
  1344. /**
  1345. * Clears the user ID from the session if it was the anonymous user. Generally
  1346. * used on out-of-tools pages to remove a user ID that could otherwise be used
  1347. * in the wrong context.
  1348. * This function is to be used in conjunction with the api_set_anonymous()
  1349. * function to simulate the user existence in case of an anonymous visit.
  1350. * @param bool database check switch - passed to api_is_anonymous()
  1351. * @return bool true if succesfully unregistered, false if not anonymous.
  1352. */
  1353. function api_clear_anonymous($db_check = false) {
  1354. global $_user;
  1355. if (api_is_anonymous($_user['user_id'], $db_check)) {
  1356. unset($_user['user_id']);
  1357. api_session_unregister('_uid');
  1358. return true;
  1359. }
  1360. return false;
  1361. }
  1362. /**
  1363. * Returns the status string corresponding to the status code
  1364. * @author Noel Dieschburg
  1365. * @param the int status code
  1366. */
  1367. function get_status_from_code($status_code) {
  1368. switch ($status_code) {
  1369. case STUDENT:
  1370. return get_lang('Student', '');
  1371. case TEACHER:
  1372. return get_lang('Teacher', '');
  1373. case COURSEMANAGER:
  1374. return get_lang('Manager', '');
  1375. case SESSIONADMIN:
  1376. return get_lang('SessionsAdmin', '');
  1377. case DRH:
  1378. return get_lang('Drh', '');
  1379. }
  1380. }
  1381. /* FAILURE MANAGEMENT */
  1382. /**
  1383. * The Failure Management module is here to compensate
  1384. * the absence of an 'exception' device in PHP 4.
  1385. */
  1386. /**
  1387. * $api_failureList - array containing all the failure recorded in order of arrival.
  1388. */
  1389. $api_failureList = array();
  1390. /**
  1391. * Fills a global array called $api_failureList
  1392. * This array collects all the failure occuring during the script runs
  1393. * The main purpose is allowing to manage the display messages externaly
  1394. * from the functions or objects. This strengthens encupsalation principle
  1395. *
  1396. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  1397. * @param string $failure_type - the type of failure
  1398. * global: array $api_failureList
  1399. * @return bolean false to stay consistent with the main script
  1400. */
  1401. function api_set_failure($failure_type) {
  1402. global $api_failureList;
  1403. $api_failureList[] = $failure_type;
  1404. return false;
  1405. }
  1406. /**
  1407. * Sets the current user as anonymous if it hasn't been identified yet. This
  1408. * function should be used inside a tool only. The function api_clear_anonymous()
  1409. * acts in the opposite direction by clearing the anonymous user's data every
  1410. * time we get on a course homepage or on a neutral page (index, admin, my space)
  1411. * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  1412. */
  1413. function api_set_anonymous() {
  1414. global $_user;
  1415. if (!empty($_user['user_id'])) {
  1416. return false;
  1417. }
  1418. $user_id = api_get_anonymous_id();
  1419. if ($user_id == 0) {
  1420. return false;
  1421. }
  1422. api_session_unregister('_user');
  1423. $_user['user_id'] = $user_id;
  1424. $_user['is_anonymous'] = true;
  1425. api_session_register('_user');
  1426. $GLOBALS['_user'] = $_user;
  1427. return true;
  1428. }
  1429. /**
  1430. * Gets the last failure stored in $api_failureList;
  1431. *
  1432. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1433. * @param void
  1434. * @return string - the last failure stored
  1435. */
  1436. function api_get_last_failure() {
  1437. global $api_failureList;
  1438. return $api_failureList[count($api_failureList) - 1];
  1439. }
  1440. /**
  1441. * Collects and manages failures occuring during script execution
  1442. * The main purpose is allowing to manage the display messages externaly
  1443. * from functions or objects. This strengthens encupsalation principle
  1444. *
  1445. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1446. * @package chamilo.library
  1447. */
  1448. class api_failure {
  1449. // TODO: $api_failureList to be hidden from global scope and to be renamed according to our coding conventions.
  1450. /**
  1451. * IMPLEMENTATION NOTE : For now the $api_failureList list is set to the
  1452. * global scope, as PHP 4 is unable to manage static variable in class. But
  1453. * this feature is awaited in PHP 5. The class is already written to minize
  1454. * the change when static class variable will be possible. And the API won't
  1455. * change.
  1456. */
  1457. public $api_failureList = array();
  1458. /**
  1459. * Piles the last failure in the failure list
  1460. *
  1461. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  1462. * @param string $failure_type - the type of failure
  1463. * @global array $api_failureList
  1464. * @return bolean false to stay consistent with the main script
  1465. */
  1466. function set_failure($failure_type) {
  1467. global $api_failureList;
  1468. $api_failureList[] = $failure_type;
  1469. return false;
  1470. }
  1471. /**
  1472. * Gets the last failure stored
  1473. *
  1474. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1475. * @param void
  1476. * @return string - the last failure stored
  1477. */
  1478. function get_last_failure() {
  1479. global $api_failureList;
  1480. if (count($api_failureList) == 0) { return ''; }
  1481. return $api_failureList[count($api_failureList) - 1];
  1482. }
  1483. }
  1484. /* CONFIGURATION SETTINGS */
  1485. /**
  1486. * Gets the current Chamilo (not PHP/cookie) session ID
  1487. * @return int O if no active session, the session ID otherwise
  1488. */
  1489. function api_get_session_id() {
  1490. return empty($_SESSION['id_session']) ? 0 : intval($_SESSION['id_session']);
  1491. }
  1492. /**
  1493. * Gets the current Chamilo (not social network) group ID
  1494. * @return int O if no active session, the session ID otherwise
  1495. */
  1496. function api_get_group_id() {
  1497. return empty($_SESSION['_gid']) ? 0 : intval($_SESSION['_gid']);
  1498. }
  1499. /**
  1500. * Gets the current or given session name
  1501. * @param int Session ID (optional)
  1502. * @return string The session name, or null if unfound
  1503. */
  1504. function api_get_session_name($session_id) {
  1505. if (empty($session_id)) {
  1506. $session_id = api_get_session_id();
  1507. if (empty($session_id)) { return null; }
  1508. }
  1509. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1510. $s = "SELECT name FROM $t WHERE id = ".(int)$session_id;
  1511. $r = Database::query($s);
  1512. $c = Database::num_rows($r);
  1513. if ($c > 0) {
  1514. //technically, there can be only one, but anyway we take the first
  1515. $rec = Database::fetch_array($r);
  1516. return $rec['name'];
  1517. }
  1518. return null;
  1519. }
  1520. /**
  1521. * Gets the session info by id
  1522. * @param int Session ID
  1523. * @return array information of the session
  1524. */
  1525. function api_get_session_info($session_id) {
  1526. $data = array();
  1527. if (!empty($session_id)) {
  1528. $session_id = intval($session_id);
  1529. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1530. $sql = "SELECT * FROM $tbl_session WHERE id = $session_id";
  1531. $result = Database::query($sql);
  1532. if (Database::num_rows($result)>0) {
  1533. $data = Database::fetch_array($result, 'ASSOC');
  1534. }
  1535. }
  1536. return $data;
  1537. }
  1538. /**
  1539. * Gets the session visibility by session id
  1540. * @param int session id
  1541. * @return int 0 = session still available, SESSION_VISIBLE_READ_ONLY = 1, SESSION_VISIBLE = 2, SESSION_INVISIBLE = 3
  1542. */
  1543. function api_get_session_visibility($session_id) {
  1544. $visibility = 0; //means that the session is still available
  1545. if (!empty($session_id)) {
  1546. $session_id = intval($session_id);
  1547. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1548. $is_coach = api_is_coach();
  1549. $condition_date_end = "";
  1550. if ($is_coach) {
  1551. //@todo use api_get_utc_datetime()
  1552. $condition_date_end = " AND (CURDATE() > (SELECT adddate(date_end,nb_days_access_after_end) FROM $tbl_session WHERE id = $session_id) AND date_end != '0000-00-00') ";
  1553. } else {
  1554. $condition_date_end = " ";
  1555. }
  1556. $sql = "SELECT visibility, date_start, date_end FROM $tbl_session
  1557. WHERE id = $session_id $condition_date_end ";
  1558. $result = Database::query($sql);
  1559. if (Database::num_rows($result) > 0 ) {
  1560. $row = Database::fetch_array($result, 'ASSOC');
  1561. $visibility = $row['visibility'];
  1562. //I don't care the field visibility
  1563. if ($row['date_start'] == '0000-00-00' && $row['date_end'] == '0000-00-00') {
  1564. $visibility = SESSION_AVAILABLE;
  1565. } else {
  1566. $time = time();
  1567. //If datestart is set
  1568. if (!empty($row['date_start']) && $row['date_start'] != '0000-00-00') {
  1569. $row['date_start'] = $row['date_start'].' 00:00:00';
  1570. if ($time > api_strtotime($row['date_start'], 'UTC')) {
  1571. $visibility = SESSION_AVAILABLE;
  1572. } else {
  1573. $visibility = SESSION_INVISIBLE;
  1574. }
  1575. }
  1576. //if date_end is set
  1577. if (!empty($row['date_end']) && $row['date_end'] != '0000-00-00') {
  1578. $row['date_end'] = $row['date_end'].' 00:00:00';
  1579. //only if date_start said that it was ok
  1580. if ($visibility == SESSION_AVAILABLE) {
  1581. $visibility = $row['visibility'];
  1582. if ($time < api_strtotime($row['date_end'], 'UTC')) {
  1583. //date still available
  1584. $visibility = SESSION_AVAILABLE;
  1585. } else {
  1586. //session ends
  1587. $visibility = $row['visibility'];
  1588. }
  1589. }
  1590. }
  1591. }
  1592. } else {
  1593. $visibility = SESSION_INVISIBLE;
  1594. }
  1595. }
  1596. return $visibility;
  1597. }
  1598. /**
  1599. * This function returns a (star) session icon if the session is not null and
  1600. * the user is not a student
  1601. * @param int Session id
  1602. * @param int User status id - if 5 (student), will return empty
  1603. * @return string Session icon
  1604. */
  1605. function api_get_session_image($session_id, $status_id) {
  1606. $session_id = (int)$session_id;
  1607. $session_img = '';
  1608. if ((int)$status_id != 5) { //check whether is not a student
  1609. if ($session_id > 0) {
  1610. $session_img = "&nbsp;&nbsp;".Display::return_icon('star.png', get_lang('SessionSpecificResource'), array('align' => 'absmiddle'), ICON_SIZE_SMALL);
  1611. }
  1612. }
  1613. return $session_img;
  1614. }
  1615. /**
  1616. * This function add an additional condition according to the session of the course
  1617. * @param int session id
  1618. * @param bool optional, true if more than one condition false if the only condition in the query
  1619. * @param bool optional, true to accept content with session=0 as well, false for strict session condition
  1620. * @return string condition of the session
  1621. */
  1622. function api_get_session_condition($session_id, $and = true, $with_base_content = false, $session_field = "session_id") {
  1623. $session_id = intval($session_id);
  1624. if (empty($session_field)) {
  1625. $session_field = "session_id";
  1626. }
  1627. //condition to show resources by session
  1628. $condition_session = '';
  1629. $condition_add = $and ? " AND " : " WHERE ";
  1630. if ($with_base_content) {
  1631. $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0) ";
  1632. } else {
  1633. $condition_session = $condition_add." $session_field = $session_id ";
  1634. }
  1635. return $condition_session;
  1636. }
  1637. /**
  1638. * This function returns information about coachs from a course in session
  1639. * @param int - optional, session id
  1640. * @param string - optional, course code
  1641. * @return array - array containing user_id, lastname, firstname, username.
  1642. */
  1643. function api_get_coachs_from_course($session_id=0,$course_code='') {
  1644. if (!empty($session_id)) {
  1645. $session_id = intval($session_id);
  1646. } else {
  1647. $session_id = api_get_session_id();
  1648. }
  1649. if (!empty($course_code)) {
  1650. $course_code = Database::escape_string($course_code);
  1651. } else {
  1652. $course_code = api_get_course_id();
  1653. }
  1654. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1655. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1656. $coaches = array();
  1657. $sql = "SELECT u.user_id,u.lastname,u.firstname,u.username FROM $tbl_user u,$tbl_session_course_user scu
  1658. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.course_code = '$course_code' AND scu.status = 2";
  1659. $rs = Database::query($sql);
  1660. if (Database::num_rows($rs) > 0) {
  1661. while ($row = Database::fetch_array($rs)) {
  1662. $coaches[] = $row;
  1663. }
  1664. return $coaches;
  1665. } else {
  1666. return false;
  1667. }
  1668. }
  1669. /**
  1670. * Returns the value of a setting from the web-adjustable admin config settings.
  1671. *
  1672. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  1673. * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
  1674. * instead of
  1675. * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
  1676. * @param string The variable name
  1677. * @param string The subkey (sub-variable) if any. Defaults to NULL
  1678. * @author René Haentjens
  1679. * @author Bart Mollet
  1680. */
  1681. function api_get_setting($variable, $key = null) {
  1682. global $_setting;
  1683. if ($variable == 'header_extra_content') {
  1684. $filename = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
  1685. if (file_exists($filename)) {
  1686. $value = file_get_contents($filename);
  1687. return $value ;
  1688. } else {
  1689. return '';
  1690. }
  1691. }
  1692. if ($variable == 'footer_extra_content') {
  1693. $filename = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt';
  1694. if (file_exists($filename)) {
  1695. $value = file_get_contents($filename);
  1696. return $value ;
  1697. } else {
  1698. return '';
  1699. }
  1700. }
  1701. $value = null;
  1702. if (is_null($key)) {
  1703. $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
  1704. } else {
  1705. if (isset($_setting[$variable][$key])) {
  1706. $value = $_setting[$variable][$key];
  1707. }
  1708. }
  1709. return $value;
  1710. }
  1711. /**
  1712. * Returns the value of a setting from the web-adjustable admin config settings.
  1713. **/
  1714. function api_get_settings_params($params) {
  1715. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1716. $result = Database::select('*', $table, array('where' => $params));
  1717. return $result;
  1718. }
  1719. /**
  1720. * Returns the value of a setting from the web-adjustable admin config settings.
  1721. **/
  1722. function api_delete_settings_params($params) {
  1723. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1724. $result = Database::delete($table, $params);
  1725. return $result;
  1726. }
  1727. /**
  1728. * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection
  1729. * @return string Escaped version of $_SERVER['PHP_SELF']
  1730. */
  1731. function api_get_self() {
  1732. return htmlentities($_SERVER['PHP_SELF']);
  1733. }
  1734. /* USER PERMISSIONS */
  1735. /**
  1736. * Checks whether current user is a platform administrator
  1737. * @return boolean True if the user has platform admin rights,
  1738. * false otherwise.
  1739. * @see usermanager::is_admin(user_id) for a user-id specific function
  1740. */
  1741. function api_is_platform_admin($allow_sessions_admins = false) {
  1742. if ($_SESSION['is_platformAdmin']) {
  1743. return true;
  1744. }
  1745. global $_user;
  1746. return $allow_sessions_admins && $_user['status'] == SESSIONADMIN;
  1747. }
  1748. function api_is_platform_admin_by_id($user_id = null) {
  1749. $user_id = intval($user_id);
  1750. if (empty($user_id)) {
  1751. $user_id = api_get_user_id();
  1752. }
  1753. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  1754. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  1755. $res = Database::query($sql);
  1756. return Database::num_rows($res) === 1;
  1757. }
  1758. /**
  1759. * Checks whether current user is allowed to create courses
  1760. * @return boolean True if the user has course creation rights,
  1761. * false otherwise.
  1762. */
  1763. function api_is_allowed_to_create_course() {
  1764. return $_SESSION['is_allowedCreateCourse'];
  1765. }
  1766. /**
  1767. * Checks whether the current user is a course administrator
  1768. * @return boolean True if current user is a course administrator
  1769. */
  1770. function api_is_course_admin() {
  1771. return $_SESSION['is_courseAdmin'];
  1772. }
  1773. /**
  1774. * Checks whether the current user is a course coach
  1775. * @return bool True if current user is a course coach
  1776. */
  1777. function api_is_course_coach() {
  1778. return $_SESSION['is_courseCoach'];
  1779. }
  1780. /**
  1781. * Checks whether the current user is a course tutor
  1782. * @return bool True if current user is a course tutor
  1783. */
  1784. function api_is_course_tutor() {
  1785. return $_SESSION['is_courseTutor'];
  1786. }
  1787. function api_get_user_platform_status($user_id = false) {
  1788. $status = array();
  1789. $user_id = intval($user_id);
  1790. if (empty($user_id)) {
  1791. $user_id = api_get_user_id();
  1792. }
  1793. if (empty($user_id)) {
  1794. return false;
  1795. }
  1796. $group_id = api_get_group_id();
  1797. $course_id = api_get_course_int_id();
  1798. $course_code= api_get_course_id();
  1799. $session_id = api_get_session_id();
  1800. //Group (in course)
  1801. if ($group_id && $course_id) {
  1802. $group_status = array();
  1803. require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
  1804. $is_subscribed = GroupManager::is_subscribed($user_id, $group_id);
  1805. if ($is_subscribed) {
  1806. $group_status = array('id'=> $group_id , 'status' => 'student');
  1807. $is_tutor = GroupManager::is_tutor_of_group($user_id, $group_id);
  1808. if ($is_tutor) {
  1809. $group_status['status'] = 'tutor';
  1810. } else {
  1811. $group_status['status'] = 'student';
  1812. }
  1813. }
  1814. $status['group'] = $group_status;
  1815. }
  1816. //Session
  1817. if ($session_id && $course_id) {
  1818. $session_status = array();
  1819. $session_status = array('id' => $session_id, 'course_id' => $course_id);
  1820. $session_user_status = SessionManager::get_user_status_in_session($user_id, $course_code, $session_id);
  1821. switch ($session_user_status) {
  1822. case 0:
  1823. $session_status['status'] = 'student';
  1824. break;
  1825. case 2:
  1826. $session_status['status'] = 'coach';
  1827. break;
  1828. }
  1829. $is_general_coach = SessionManager::user_is_general_coach($user_id, $session_id);
  1830. if ($is_general_coach) {
  1831. $session_status['status'] = 'general_coach';
  1832. }
  1833. $status['session'] = $session_status;
  1834. } elseif($course_id) {
  1835. //Course
  1836. $course_status = array();
  1837. if ($course_id) {
  1838. $user_course_status = CourseManager::get_user_in_course_status($user_id, $course_code);
  1839. if ($user_course_status) {
  1840. $course_status = array('id'=> $course_id);
  1841. switch($user_course_status) {
  1842. case 1;
  1843. $course_status['status'] = 'teacher';
  1844. break;
  1845. case 5;
  1846. $course_status['status'] = 'student';
  1847. //check if tutor
  1848. $tutor_course_status = CourseManager::get_tutor_in_course_status($user_id, $course_code);
  1849. if ($tutor_course_status) {
  1850. $course_status['status'] = 'tutor';
  1851. }
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. $status['course'] = $course_status;
  1857. }
  1858. return $status;
  1859. }
  1860. /**
  1861. * Checks whether the current user is a course or session coach
  1862. * @param int - optional, session id
  1863. * @param string - optional, course code
  1864. * @return boolean True if current user is a course or session coach
  1865. */
  1866. function api_is_coach($session_id = 0, $course_code = '') {
  1867. //@todo Not sure about this one
  1868. /*if (api_is_platform_admin()) {
  1869. return true;
  1870. }*/
  1871. if (!empty($session_id)) {
  1872. $session_id = intval($session_id);
  1873. } else {
  1874. $session_id = api_get_session_id();
  1875. }
  1876. if (!empty($course_code)) {
  1877. $course_code = Database::escape_string($course_code);
  1878. } else {
  1879. $course_code = api_get_course_id();
  1880. }
  1881. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1882. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1883. $sessionIsCoach = null;
  1884. if (!empty($course_code)) {
  1885. $sql = "SELECT DISTINCT id, name, date_start, date_end
  1886. FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  1887. ON session_rc_ru.id_user = '".api_get_user_id()."'
  1888. WHERE session_rc_ru.course_code = '$course_code' AND session_rc_ru.status = 2 AND session_rc_ru.id_session = '$session_id'";
  1889. $result = Database::query($sql);
  1890. $sessionIsCoach = Database::store_result($result);
  1891. }
  1892. if (!empty($session_id)) {
  1893. $sql = "SELECT DISTINCT id, name, date_start, date_end
  1894. FROM $session_table
  1895. WHERE session.id_coach = '".api_get_user_id()."' AND id = '$session_id'
  1896. ORDER BY date_start, date_end, name";
  1897. $result = Database::query($sql);
  1898. if (!empty($sessionIsCoach)) {
  1899. $sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
  1900. } else {
  1901. $sessionIsCoach = Database::store_result($result);
  1902. }
  1903. }
  1904. return (count($sessionIsCoach) > 0);
  1905. }
  1906. /**
  1907. * Checks whether the current user is a session administrator
  1908. * @return boolean True if current user is a course administrator
  1909. */
  1910. function api_is_session_admin() {
  1911. global $_user;
  1912. return $_user['status'] == SESSIONADMIN;
  1913. }
  1914. /**
  1915. * Checks whether the current user is a human resources manager
  1916. * @return boolean True if current user is a human resources manager
  1917. */
  1918. function api_is_drh() {
  1919. global $_user;
  1920. return $_user['status'] == DRH;
  1921. }
  1922. /**
  1923. * Checks whether the current user is a student
  1924. * @return boolean True if current user is a human resources manager
  1925. */
  1926. function api_is_student() {
  1927. global $_user;
  1928. return $_user['status'] == STUDENT;
  1929. }
  1930. /**
  1931. * Checks whether the current user is a teacher
  1932. * @return boolean True if current user is a human resources manager
  1933. */
  1934. function api_is_teacher() {
  1935. global $_user;
  1936. return $_user['status'] == COURSEMANAGER;
  1937. }
  1938. /**
  1939. * This function checks whether a session is assigned into a category
  1940. * @param int - session id
  1941. * @param string - category name
  1942. * @return bool - true if is found, otherwise false
  1943. */
  1944. function api_is_session_in_category($session_id, $category_name) {
  1945. $session_id = intval($session_id);
  1946. $category_name = Database::escape_string($category_name);
  1947. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1948. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1949. $sql = "select 1 FROM $tbl_session WHERE $session_id IN (SELECT s.id FROM $tbl_session s, $tbl_session_category sc WHERE s.session_category_id = sc.id AND sc.name LIKE '%$category_name' )";
  1950. $rs = Database::query($sql);
  1951. if (Database::num_rows($rs) > 0) {
  1952. return true;
  1953. } else {
  1954. return false;
  1955. }
  1956. }
  1957. /* DISPLAY OPTIONS
  1958. student view, title, message boxes,... */
  1959. /**
  1960. * Displays the title of a tool.
  1961. * Normal use: parameter is a string:
  1962. * api_display_tool_title("My Tool")
  1963. *
  1964. * Optionally, there can be a subtitle below
  1965. * the normal title, and / or a supra title above the normal title.
  1966. *
  1967. * e.g. supra title:
  1968. * group
  1969. * GROUP PROPERTIES
  1970. *
  1971. * e.g. subtitle:
  1972. * AGENDA
  1973. * calender & events tool
  1974. *
  1975. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1976. * @param mixed $title_element - it could either be a string or an array
  1977. * containing 'supraTitle', 'mainTitle',
  1978. * 'subTitle'
  1979. * @return void
  1980. */
  1981. function api_display_tool_title($title_element) {
  1982. if (is_string($title_element)) {
  1983. $tit = $title_element;
  1984. unset ($title_element);
  1985. $title_element['mainTitle'] = $tit;
  1986. }
  1987. echo '<h2>';
  1988. if (!empty($title_element['supraTitle'])) {
  1989. echo '<small>'.$title_element['supraTitle'].'</small><br />';
  1990. }
  1991. if (!empty($title_element['mainTitle'])) {
  1992. echo $title_element['mainTitle'];
  1993. }
  1994. if (!empty($title_element['subTitle'])) {
  1995. echo '<br /><small>'.$title_element['subTitle'].'</small>';
  1996. }
  1997. echo '</h2>';
  1998. }
  1999. /**
  2000. * Displays options for switching between student view and course manager view
  2001. *
  2002. * Changes in version 1.2 (Patrick Cool)
  2003. * Student view switch now behaves as a real switch. It maintains its current state until the state
  2004. * is changed explicitly
  2005. *
  2006. * Changes in version 1.1 (Patrick Cool)
  2007. * student view now works correctly in subfolders of the document tool
  2008. * student view works correctly in the new links tool
  2009. *
  2010. * Example code for using this in your tools:
  2011. * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
  2012. * // display_tool_view_option($isStudentView);
  2013. * //}
  2014. * //and in later sections, use api_is_allowed_to_edit()
  2015. *
  2016. * @author Roan Embrechts
  2017. * @author Patrick Cool
  2018. * @version 1.2
  2019. * @todo rewrite code so it is easier to understand
  2020. */
  2021. function api_display_tool_view_option() {
  2022. if (api_get_setting('student_view_enabled') != 'true') {
  2023. return '';
  2024. }
  2025. $output_string = '';
  2026. $sourceurl = '';
  2027. $is_framed = false;
  2028. // Exceptions apply for all multi-frames pages
  2029. if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) { // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
  2030. $is_framed = true;
  2031. return '';
  2032. }
  2033. /*// Uncomment to remove student view link from document view page
  2034. if (strpos($_SERVER['REQUEST_URI'], 'document/headerpage.php') !== false) {
  2035. $sourceurl = str_replace('document/headerpage.php', 'document/showinframes.php', $_SERVER['REQUEST_URI']);
  2036. //showinframes doesn't handle student view anyway...
  2037. //return '';
  2038. $is_framed = true;
  2039. }*/
  2040. // Uncomment to remove student view link from document view page
  2041. if (strpos($_SERVER['REQUEST_URI'], 'newscorm/lp_header.php') !== false) {
  2042. if (empty($_GET['lp_id'])) {
  2043. return '';
  2044. }
  2045. $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
  2046. $sourceurl = str_replace('newscorm/lp_header.php', 'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview']=='studentview' ? 'false' : 'true'), $sourceurl);
  2047. //showinframes doesn't handle student view anyway...
  2048. //return '';
  2049. $is_framed = true;
  2050. }
  2051. // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  2052. if (!$is_framed) {
  2053. if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
  2054. $sourceurl = api_get_self().'?'.api_get_cidreq();
  2055. } else {
  2056. $sourceurl = $_SERVER['REQUEST_URI'];
  2057. //$sourceurl = str_replace('&', '&amp;', $sourceurl);
  2058. }
  2059. }
  2060. if (!empty($_SESSION['studentview'])) {
  2061. if ($_SESSION['studentview'] == 'studentview') {
  2062. // We have to remove the isStudentView=true from the $sourceurl
  2063. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2064. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2065. $output_string .= '<a href="'.$sourceurl.'&isStudentView=false" target="_self">'.get_lang('CourseManagerview').'</a>';
  2066. } elseif ($_SESSION['studentview'] == 'teacherview') {
  2067. // Switching to teacherview
  2068. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2069. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2070. $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_self">'.get_lang('StudentView').'</a>';
  2071. }
  2072. } else {
  2073. $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_self">'.get_lang('StudentView').'</a>';
  2074. }
  2075. return $output_string;
  2076. }
  2077. /**
  2078. * Displays the contents of an array in a messagebox.
  2079. * @param array $info_array An array with the messages to show
  2080. */
  2081. function api_display_array($info_array) {
  2082. $message = '';
  2083. if(is_array($info_array)) {
  2084. foreach ($info_array as $element) {
  2085. $message .= $element.'<br />';
  2086. }
  2087. }
  2088. Display :: display_normal_message($message);
  2089. }
  2090. /**
  2091. * Displays debug info
  2092. * @param string $debug_info The message to display
  2093. * @author Roan Embrechts
  2094. * @version 1.1, March 2004
  2095. */
  2096. function api_display_debug_info($debug_info) {
  2097. $message = '<i>Debug info</i><br />';
  2098. $message .= $debug_info;
  2099. Display :: display_normal_message($message);
  2100. }
  2101. // TODO: This is for the permission section.
  2102. /**
  2103. * Function that removes the need to directly use is_courseAdmin global in
  2104. * tool scripts. It returns true or false depending on the user's rights in
  2105. * this particular course.
  2106. * Optionally checking for tutor and coach roles here allows us to use the
  2107. * student_view feature altogether with these roles as well.
  2108. * @param bool Whether to check if the user has the tutor role
  2109. * @param bool Whether to check if the user has the coach role
  2110. * @param bool Whether to check if the user has the session coach role
  2111. *
  2112. * @author Roan Embrechts
  2113. * @author Patrick Cool
  2114. * @version 1.1, February 2004
  2115. * @return boolean, true: the user has the rights to edit, false: he does not
  2116. */
  2117. function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach = false) {
  2118. $my_session_id = api_get_session_id();
  2119. $is_allowed_coach_to_edit = api_is_coach();
  2120. $session_visibility = api_get_session_visibility($my_session_id);
  2121. $is_courseAdmin = api_is_course_admin() || api_is_platform_admin();
  2122. if (!$is_courseAdmin && $tutor) { // If we also want to check if the user is a tutor...
  2123. $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
  2124. }
  2125. if (!$is_courseAdmin && $coach) { // If we also want to check if the user is a coach...';
  2126. // Check if session visibility is read only for coaches.
  2127. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2128. $is_allowed_coach_to_edit = false;
  2129. }
  2130. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') { // Check if coach is allowed to edit a course.
  2131. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  2132. } else {
  2133. $is_courseAdmin = $is_courseAdmin;
  2134. }
  2135. }
  2136. if (!$is_courseAdmin && $session_coach) {
  2137. $is_courseAdmin = $is_courseAdmin || api_is_coach();
  2138. }
  2139. if (api_get_setting('student_view_enabled') == 'true') { // Check if the student_view is enabled, and if so, if it is activated.
  2140. if (!empty($my_session_id)) {
  2141. // Check if session visibility is read only for coachs
  2142. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2143. $is_allowed_coach_to_edit = false;
  2144. }
  2145. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') { // Check if coach is allowed to edit a course.
  2146. $is_allowed = $is_allowed_coach_to_edit;
  2147. } else {
  2148. $is_allowed = false;
  2149. }
  2150. $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
  2151. } else {
  2152. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
  2153. }
  2154. return $is_allowed;
  2155. } else {
  2156. return $is_courseAdmin;
  2157. }
  2158. }
  2159. /**
  2160. * Checks if a student can edit contents in a session depending
  2161. * on the session visibility
  2162. * @param bool Whether to check if the user has the tutor role
  2163. * @param bool Whether to check if the user has the coach role
  2164. * @return boolean, true: the user has the rights to edit, false: he does not
  2165. */
  2166. function api_is_allowed_to_session_edit($tutor = false, $coach = false) {
  2167. if (api_is_allowed_to_edit($tutor, $coach)) {
  2168. // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
  2169. return true;
  2170. } else {
  2171. if (api_get_session_id() == 0) {
  2172. // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
  2173. return true;
  2174. } else {
  2175. // I'm in a session and I'm a student
  2176. $session_id = api_get_session_id();
  2177. // Get the session visibility
  2178. $session_visibility = api_get_session_visibility($session_id); // if 5 the session is still available.
  2179. //@todo We could load the session_rel_course_rel_user permission to increase the level of detail.
  2180. //echo api_get_user_id();
  2181. //echo api_get_course_id();
  2182. switch ($session_visibility) {
  2183. case SESSION_VISIBLE_READ_ONLY: // 1
  2184. return false;
  2185. case SESSION_VISIBLE: // 2
  2186. return true;
  2187. case SESSION_INVISIBLE: // 3
  2188. return false;
  2189. case SESSION_AVAILABLE: //5
  2190. return true;
  2191. }
  2192. }
  2193. }
  2194. }
  2195. /**
  2196. * Checks whether the user is allowed in a specific tool for a specific action
  2197. * @param $tool the tool we are checking if the user has a certain permission
  2198. * @param $action the action we are checking (add, edit, delete, move, visibility)
  2199. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2200. * @version 1.0
  2201. */
  2202. function api_is_allowed($tool, $action, $task_id = 0) {
  2203. global $_course;
  2204. global $_user;
  2205. if (api_is_course_admin()) {
  2206. return true;
  2207. }
  2208. //if (!$_SESSION['total_permissions'][$_course['code']] and $_course)
  2209. if (is_array($_course) and count($_course) > 0) {
  2210. require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php';
  2211. require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
  2212. // Getting the permissions of this user.
  2213. if ($task_id == 0) {
  2214. $user_permissions = get_permissions('user', $_user['user_id']);
  2215. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  2216. }
  2217. // Getting the permissions of the task.
  2218. if ($task_id != 0) {
  2219. $task_permissions = get_permissions('task', $task_id);
  2220. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  2221. }
  2222. //print_r($_SESSION['total_permissions']);
  2223. // Getting the permissions of the groups of the user
  2224. //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  2225. //foreach($groups_of_user as $group)
  2226. // $this_group_permissions = get_permissions('group', $group);
  2227. // Getting the permissions of the courseroles of the user
  2228. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  2229. // Getting the permissions of the platformroles of the user
  2230. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  2231. // Getting the permissions of the roles of the groups of the user
  2232. //foreach($groups_of_user as $group)
  2233. // $this_group_courserole_permissions = get_roles_permissions('group', $group);
  2234. // Getting the permissions of the platformroles of the groups of the user
  2235. //foreach($groups_of_user as $group)
  2236. // $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  2237. }
  2238. // If the permissions are limited, we have to map the extended ones to the limited ones.
  2239. if (api_get_setting('permissions') == 'limited') {
  2240. if ($action == 'Visibility') {
  2241. $action = 'Edit';
  2242. }
  2243. if ($action == 'Move') {
  2244. $action = 'Edit';
  2245. }
  2246. }
  2247. // The session that contains all the permissions already exists for this course
  2248. // so there is no need to requery everything.
  2249. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  2250. if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
  2251. if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
  2252. return true;
  2253. } else {
  2254. return false;
  2255. }
  2256. }
  2257. }
  2258. /**
  2259. * Tells whether this user is an anonymous user
  2260. * @param int User ID (optional, will take session ID if not provided)
  2261. * @param bool Whether to check in the database (true) or simply in the session (false) to see if the current user is the anonymous user
  2262. * @return bool true if this user is anonymous, false otherwise
  2263. */
  2264. function api_is_anonymous($user_id = null, $db_check = false) {
  2265. if (!isset($user_id)) {
  2266. $user_id = api_get_user_id();
  2267. }
  2268. if ($db_check) {
  2269. $info = api_get_user_info($user_id);
  2270. if ($info['status'] == 6) {
  2271. return true;
  2272. }
  2273. }
  2274. global $_user;
  2275. if (!isset($_user)) {
  2276. // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
  2277. // Occurs in agenda for admin links - YW
  2278. global $use_anonymous;
  2279. if (isset($use_anonymous) && $use_anonymous) {
  2280. api_set_anonymous();
  2281. }
  2282. return true;
  2283. }
  2284. return isset($_user['is_anonymous']) && $_user['is_anonymous'] === true;
  2285. }
  2286. /**
  2287. * Displays message "You are not allowed here..." and exits the entire script.
  2288. * @param bool Whether or not to print headers (default = false -> does not print them)
  2289. *
  2290. * @author Roan Embrechts
  2291. * @author Yannick Warnier
  2292. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2293. *
  2294. * @version 1.0, February 2004
  2295. * @version dokeos 1.8, August 2006
  2296. */
  2297. function api_not_allowed($print_headers = false) {
  2298. $home_url = api_get_path(WEB_PATH);
  2299. $user = api_get_user_id(); //0 if not defined
  2300. $course = api_get_course_id();
  2301. global $this_section;
  2302. if (api_get_setting('use_custom_pages') == 'true' && !isset($_SESSION['_user']['user_id'])) {
  2303. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  2304. require_once api_get_path(LIBRARY_PATH).'custompages.lib.php';
  2305. CustomPages::displayPage('index-unlogged');
  2306. exit;
  2307. }
  2308. $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
  2309. if ($origin == 'learnpath') {
  2310. $htmlHeadXtra[]= '<style type="text/css" media="screen, projection">
  2311. /*<![CDATA[*/
  2312. @import "'.api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/default.css";
  2313. /*]]>*/
  2314. </style>';
  2315. }
  2316. $msg = Display::return_message(get_lang('NotAllowedClickBack'), 'error', false);
  2317. $msg = Display::div($msg, array('align'=>'center'));
  2318. $show_headers = 0;
  2319. if ((!headers_sent() || $print_headers) && $origin != 'learnpath') {
  2320. $show_headers = 1;
  2321. }
  2322. $tpl = new Template(null, $show_headers, $show_headers);
  2323. $tpl->assign('content', $msg);
  2324. if (($user!=0 && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) {
  2325. // if the access is not authorized and there is some login information
  2326. // but the cidReq is not found, assume we are missing course data and send the user
  2327. // to the user_portal
  2328. $tpl->display_one_col_template();
  2329. exit;
  2330. }
  2331. if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) {
  2332. //only display form and return to the previous URL if there was a course ID included
  2333. if ($user!=0 && !api_is_anonymous()) {
  2334. //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
  2335. $tpl->assign('content', $msg);
  2336. $tpl->display_one_col_template();
  2337. exit;
  2338. }
  2339. // If the user has no user ID, then his session has expired
  2340. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  2341. $form = new FormValidator('formLogin', 'post', api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']), null, array('class'=>'form-stacked'));
  2342. $form->addElement('text', 'login', get_lang('UserName'), array('size' => 17));
  2343. $form->addElement('password', 'password', get_lang('Password'), array('size' => 17));
  2344. $form->addElement('style_submit_button', 'submitAuth', get_lang('LoginEnter'),'class="btn"');
  2345. $content = Display::return_message(get_lang('NotAllowed').'<br />'.get_lang('PleaseLoginAgainFromFormBelow').'<br />', 'error', false);
  2346. $content .= '<div style="margin: 0 auto; width: 200px;">';
  2347. $content .= $form->return_form();
  2348. $content .='</div>';
  2349. $tpl->assign('content', $content);
  2350. $tpl->display_one_col_template();
  2351. exit;
  2352. }
  2353. if ($user!=0 && !api_is_anonymous()) {
  2354. $tpl->display_one_col_template();
  2355. exit;
  2356. }
  2357. // Check if the cookies are enabled. If are enabled and if no course ID was included in the requested URL, then the user has either lost his session or is anonymous, so redirect to homepage
  2358. if( !isset($_COOKIE["TestCookie"]) && empty($_COOKIE["TestCookie"]) ) {
  2359. $msg = Display::return_message(get_lang('NoCookies').'<br /><br /><a href="'.$home_url.'">'.get_lang('BackTo').' '.get_lang('CampusHomepage').'</a><br />', 'error', false);
  2360. }
  2361. else {
  2362. $msg = Display::return_message(get_lang('NotAllowed').'<br /><br /><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
  2363. }
  2364. $msg = Display::div($msg, array('align'=>'center'));
  2365. $tpl->assign('content', $msg);
  2366. $tpl->display_one_col_template();
  2367. exit;
  2368. }
  2369. /* WHAT'S NEW
  2370. functions for the what's new icons
  2371. in the user course list */
  2372. /**
  2373. * Gets a UNIX timestamp from a database (MySQL) datetime format string
  2374. * @param $last_post_datetime standard output date in a sql query
  2375. * @return unix timestamp
  2376. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  2377. * @version October 2003
  2378. * @desc convert sql date to unix timestamp
  2379. */
  2380. function convert_sql_date($last_post_datetime) {
  2381. list ($last_post_date, $last_post_time) = split(' ', $last_post_datetime);
  2382. list ($year, $month, $day) = explode('-', $last_post_date);
  2383. list ($hour, $min, $sec) = explode(':', $last_post_time);
  2384. return mktime((int)$hour, (int)$min, (int)$sec, (int)$month, (int)$day, (int)$year);
  2385. }
  2386. /**
  2387. * Gets a database (MySQL) datetime format string from a UNIX timestamp
  2388. * @param int UNIX timestamp, as generated by the time() function. Will be generated if parameter not provided
  2389. * @return string MySQL datetime format, like '2009-01-30 12:23:34'
  2390. */
  2391. function api_get_datetime($time = null) {
  2392. if (!isset($time)) { $time = time(); }
  2393. return date('Y-m-d H:i:s', $time);
  2394. }
  2395. /**
  2396. * Gets item visibility from the item_property table
  2397. *
  2398. * Getting the visibility is done by getting the last updated visibility entry,
  2399. * using the largest session ID found if session 0 and another was found (meaning
  2400. * the only one that is actually from the session, in case there are results from
  2401. * session 0 *AND* session n).
  2402. * @param array Course properties array (result of api_get_course_info())
  2403. * @param string Tool (learnpath, document, etc)
  2404. * @param int The item ID in the given tool
  2405. * @param int The session ID (optional)
  2406. * @return int -1 on error, 0 if invisible, 1 if visible
  2407. */
  2408. function api_get_item_visibility($_course, $tool, $id, $session=0) {
  2409. if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) { return -1; }
  2410. $tool = Database::escape_string($tool);
  2411. $id = Database::escape_string($id);
  2412. $session = (int) $session;
  2413. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2414. $course_id = $_course['real_id'];
  2415. $sql = "SELECT visibility FROM $TABLE_ITEMPROPERTY
  2416. WHERE c_id = $course_id AND
  2417. tool = '$tool' AND
  2418. ref = $id AND
  2419. (id_session = $session OR id_session = 0)
  2420. ORDER BY id_session DESC, lastedit_date DESC";
  2421. $res = Database::query($sql);
  2422. if ($res === false || Database::num_rows($res) == 0) { return -1; }
  2423. $row = Database::fetch_array($res);
  2424. return $row['visibility'];
  2425. }
  2426. /**
  2427. * Updates or adds item properties to the Item_propetry table
  2428. * Tool and lastedit_type are language independant strings (langvars->get_lang!)
  2429. *
  2430. * @param $_course : array with course properties
  2431. * @param $tool : tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2432. * @param $item_id : id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2433. * @param $lastedit_type : add or update action (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  2434. * (2) "delete"; (3) "visible"; (4) "invisible";
  2435. * @param $user_id : id of the editing/adding user
  2436. * @param $to_group_id : id of the intended group ( 0 = for everybody), only relevant for $type (1)
  2437. * @param $to_user_id : id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  2438. * @param string $start_visible 0000-00-00 00:00:00 format
  2439. * @param unknown_type $end_visible 0000-00-00 00:00:00 format
  2440. * @return boolean False if update fails.
  2441. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  2442. * @version January 2005
  2443. * @desc update the item_properties table (if entry not exists, insert) of the course
  2444. */
  2445. function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $user_id, $to_group_id = 0, $to_user_id = null, $start_visible = 0, $end_visible = 0, $session_id = 0) {
  2446. // Definition of variables.
  2447. $tool = Database::escape_string($tool);
  2448. $item_id = Database::escape_string($item_id);
  2449. $lastedit_type = Database::escape_string($lastedit_type);
  2450. $user_id = Database::escape_string($user_id);
  2451. $to_group_id = Database::escape_string($to_group_id);
  2452. $to_user_id = Database::escape_string($to_user_id);
  2453. $start_visible = Database::escape_string($start_visible);
  2454. $end_visible = Database::escape_string($end_visible);
  2455. $start_visible = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible;
  2456. $end_visible = ($end_visible == 0) ? '0000-00-00 00:00:00' : $end_visible;
  2457. $to_filter = '';
  2458. $time = api_get_utc_datetime();
  2459. if (!empty($session_id)) {
  2460. $session_id = intval($session_id);
  2461. } else {
  2462. $session_id = api_get_session_id();
  2463. }
  2464. // Definition of tables.
  2465. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2466. if ($to_user_id <= 0) {
  2467. $to_user_id = null; // No to_user_id set
  2468. }
  2469. if (!is_null($to_user_id)) {
  2470. // $to_user_id has more priority than $to_group_id
  2471. $to_field = 'to_user_id';
  2472. $to_value = $to_user_id;
  2473. } else {
  2474. // $to_user_id is not set.
  2475. $to_field = 'to_group_id';
  2476. $to_value = $to_group_id;
  2477. }
  2478. // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  2479. $condition_session = '';
  2480. if (!empty($session_id)) {
  2481. $condition_session = " AND id_session = '$session_id' ";
  2482. }
  2483. $course_id = $_course['real_id'];
  2484. $filter = " c_id = $course_id AND tool='$tool' AND ref='$item_id' $condition_session ";
  2485. if ($item_id == '*') {
  2486. $filter = " c_id = $course_id AND tool='$tool' AND visibility<>'2' $condition_session"; // For all (not deleted) items of the tool
  2487. }
  2488. // Check whether $to_user_id and $to_group_id are passed in the function call.
  2489. // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  2490. if (is_null($to_user_id) && is_null($to_group_id)) {
  2491. $to_group_id = 0;
  2492. }
  2493. if (!is_null($to_user_id)) {
  2494. $to_filter = " AND to_user_id='$to_user_id' $condition_session"; // Set filter to intended user.
  2495. } else {
  2496. if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
  2497. $to_filter = " AND to_group_id='$to_group_id' $condition_session"; // Set filter to intended group.
  2498. }
  2499. }
  2500. // Update if possible
  2501. $set_type = '';
  2502. switch ($lastedit_type) {
  2503. case 'delete' : // delete = make item only visible for the platform admin.
  2504. $visibility = '2';
  2505. if (!empty($session_id)) {
  2506. // Check whether session id already exist into itemp_properties for updating visibility or add it.
  2507. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY
  2508. WHERE c_id = $course_id AND tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2509. $rs = Database::query($sql);
  2510. if (Database::num_rows($rs) > 0) {
  2511. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2512. SET lastedit_type = '".str_replace('_', '', ucwords($tool))."Deleted',
  2513. lastedit_date = '$time',
  2514. lastedit_user_id = '$user_id',
  2515. visibility = '$visibility',
  2516. id_session = '$session_id' $set_type
  2517. WHERE $filter";
  2518. } else {
  2519. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2520. VALUES ($course_id, '$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value', '$visibility', '$start_visible','$end_visible', '$session_id')";
  2521. }
  2522. } else {
  2523. $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2524. WHERE $filter";
  2525. }
  2526. break;
  2527. case 'visible' : // Change item to visible.
  2528. $visibility = '1';
  2529. if (!empty($session_id)) {
  2530. // Check whether session id already exist into itemp_properties for updating visibility or add it.
  2531. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY WHERE c_id=$course_id AND tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2532. $rs = Database::query($sql);
  2533. if (Database::num_rows($rs) > 0) {
  2534. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2535. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Visible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
  2536. WHERE $filter";
  2537. } else {
  2538. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2539. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2540. }
  2541. } else {
  2542. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2543. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Visible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2544. WHERE $filter";
  2545. }
  2546. break;
  2547. case 'invisible' : // Change item to invisible.
  2548. $visibility = '0';
  2549. if (!empty($session_id)) {
  2550. // Check whether session id already exist into itemp_properties for updating visibility or add it
  2551. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY WHERE c_id=$course_id AND tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2552. $rs = Database::query($sql);
  2553. if (Database::num_rows($rs) > 0) {
  2554. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2555. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Invisible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
  2556. WHERE $filter";
  2557. } else {
  2558. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2559. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2560. }
  2561. } else {
  2562. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2563. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Invisible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2564. WHERE $filter";
  2565. }
  2566. break;
  2567. default : // The item will be added or updated.
  2568. $set_type = ", lastedit_type='$lastedit_type' ";
  2569. $visibility = '1';
  2570. $filter .= $to_filter;
  2571. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2572. SET lastedit_date='$time', lastedit_user_id='$user_id' $set_type
  2573. WHERE $filter";
  2574. }
  2575. $res = Database::query($sql);
  2576. // Insert if no entries are found (can only happen in case of $lastedit_type switch is 'default').
  2577. if (Database::affected_rows() == 0) {
  2578. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2579. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2580. $res = Database::query($sql);
  2581. if (!$res) {
  2582. return false;
  2583. }
  2584. }
  2585. return true;
  2586. }
  2587. /**
  2588. * Gets item property by tool
  2589. * @param string course code
  2590. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2591. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2592. */
  2593. function api_get_item_property_by_tool($tool, $course_code, $session_id = null) {
  2594. $course_info = api_get_course_info($course_code);
  2595. $tool = Database::escape_string($tool);
  2596. // Definition of tables.
  2597. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2598. $session_condition = '';
  2599. $session_id = intval($session_id);
  2600. $session_condition = ' AND id_session = '.$session_id;
  2601. $course_id = $course_info['real_id'];
  2602. $sql = "SELECT * FROM $item_property_table WHERE c_id = $course_id AND tool = '$tool' $session_condition ";
  2603. $rs = Database::query($sql);
  2604. $item_property_id = '';
  2605. $list = array();
  2606. if (Database::num_rows($rs) > 0) {
  2607. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  2608. $list[] = $row;
  2609. }
  2610. }
  2611. return $list;
  2612. }
  2613. /**
  2614. * Gets item property id from tool of a course
  2615. * @param string course code
  2616. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2617. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2618. */
  2619. function api_get_item_property_id($course_code, $tool, $ref) {
  2620. $course_info = api_get_course_info($course_code);
  2621. $tool = Database::escape_string($tool);
  2622. $ref = intval($ref);
  2623. // Definition of tables.
  2624. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2625. $course_id = $course_info['real_id'];
  2626. $sql = "SELECT id FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = '$ref'";
  2627. $rs = Database::query($sql);
  2628. $item_property_id = '';
  2629. if (Database::num_rows($rs) > 0) {
  2630. $row = Database::fetch_array($rs);
  2631. $item_property_id = $row['id'];
  2632. }
  2633. return $item_property_id;
  2634. }
  2635. /**
  2636. *
  2637. * Inserts a record in the track_e_item_property table (No update)
  2638. *
  2639. */
  2640. function api_track_item_property_update($tool, $ref, $title, $content, $progress) {
  2641. $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  2642. $course_id = api_get_real_course_id(); //numeric
  2643. $course_code = api_get_course_id(); //alphanumeric
  2644. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  2645. if (!empty($item_property_id)) {
  2646. $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
  2647. course_id = '$course_id',
  2648. item_property_id = '$item_property_id',
  2649. title = '".Database::escape_string($title)."',
  2650. content = '".Database::escape_string($content)."',
  2651. progress = '".intval($progress)."',
  2652. lastedit_date = '".api_get_utc_datetime()."',
  2653. lastedit_user_id = '".api_get_user_id()."',
  2654. session_id = '".api_get_session_id()."'";
  2655. Database::query($sql);
  2656. $affected_rows = Database::affected_rows();
  2657. return $affected_rows;
  2658. }
  2659. return false;
  2660. }
  2661. function api_get_track_item_property_history($tool, $ref) {
  2662. $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  2663. $course_id = api_get_real_course_id(); //numeric
  2664. $course_code = api_get_course_id(); //alphanumeric
  2665. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  2666. $sql = "SELECT * FROM $tbl_stats_item_property WHERE item_property_id = $item_property_id AND course_id = $course_id ORDER BY lastedit_date DESC";
  2667. $result = Database::query($sql);
  2668. $result = Database::store_result($result,'ASSOC');
  2669. return $result;
  2670. }
  2671. /**
  2672. * Gets item property data from tool of a course id
  2673. * @param int course id
  2674. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2675. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2676. */
  2677. function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0) {
  2678. $course_info = api_get_course_info_by_id($course_id);
  2679. if (empty($course_info)) {
  2680. return false;
  2681. }
  2682. $tool = Database::escape_string($tool);
  2683. $ref = intval($ref);
  2684. $course_id = intval($course_id);
  2685. // Definition of tables.
  2686. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2687. $course_id = $course_info['real_id'];
  2688. $sql = "SELECT * FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = $ref ";
  2689. if (!empty($session_id)) {
  2690. $session_id = intval($session_id);
  2691. $sql .= "AND id_session = $session_id ";
  2692. }
  2693. $rs = Database::query($sql);
  2694. $row = array();
  2695. if (Database::num_rows($rs) > 0) {
  2696. $row = Database::fetch_array($rs,'ASSOC');
  2697. }
  2698. return $row;
  2699. }
  2700. /* Language Dropdown */
  2701. /**
  2702. * Displays a combobox so the user can select his/her preferred language.
  2703. * @param string The desired name= value for the select
  2704. * @return string
  2705. */
  2706. function api_get_languages_combo($name = 'language') {
  2707. $ret = '';
  2708. $platformLanguage = api_get_setting('platformLanguage');
  2709. // Retrieve a complete list of all the languages.
  2710. $language_list = api_get_languages();
  2711. if (count($language_list['name']) < 2) {
  2712. return $ret;
  2713. }
  2714. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  2715. if (isset($_SESSION['user_language_choice'])) {
  2716. $default = $_SESSION['user_language_choice'];
  2717. } else {
  2718. $default = $platformLanguage;
  2719. }
  2720. $languages = $language_list['name'];
  2721. $folder = $language_list['folder'];
  2722. $ret .= '<select name="'.$name.'" id="language_chosen" class="chzn-select" >';
  2723. foreach ($languages as $key => $value) {
  2724. if ($folder[$key] == $default) {
  2725. $selected = ' selected="selected"';
  2726. } else {
  2727. $selected = '';
  2728. }
  2729. $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
  2730. }
  2731. $ret .= '</select>';
  2732. return $ret;
  2733. }
  2734. /**
  2735. * Displays a form (drop down menu) so the user can select his/her preferred language.
  2736. * The form works with or without javascript
  2737. * @param boolean Hide form if only one language available (defaults to false = show the box anyway)
  2738. * @return void Display the box directly
  2739. */
  2740. function api_display_language_form($hide_if_no_choice = false) {
  2741. // Retrieve a complete list of all the languages.
  2742. $language_list = api_get_languages();
  2743. if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
  2744. return; //don't show any form
  2745. }
  2746. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  2747. if (isset($_SESSION['user_language_choice'])) {
  2748. $user_selected_language = $_SESSION['user_language_choice'];
  2749. }
  2750. if (empty($user_selected_language)) {
  2751. $user_selected_language = api_get_setting('platformLanguage');
  2752. }
  2753. $original_languages = $language_list['name'];
  2754. $folder = $language_list['folder']; // This line is probably no longer needed.
  2755. $html = '
  2756. <script type="text/javascript">
  2757. <!--
  2758. function jumpMenu(targ,selObj,restore){ // v3.0
  2759. eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
  2760. if (restore) selObj.selectedIndex=0;
  2761. }
  2762. //-->
  2763. </script>';
  2764. $html .= '<form id="lang_form" name="lang_form" method="post" action="'.api_get_self().'">';
  2765. $html .= '<select id="language_list" class="chzn-select" name="language_list" onchange="javascript: jumpMenu(\'parent\',this,0);">';
  2766. foreach ($original_languages as $key => $value) {
  2767. if ($folder[$key] == $user_selected_language) {
  2768. $option_end = ' selected="selected" >';
  2769. } else {
  2770. $option_end = '>';
  2771. }
  2772. $html .= '<option value="'.api_get_self().'?language='.$folder[$key].'"'.$option_end;
  2773. //echo substr($value, 0, 16); // Cut string to keep 800x600 aspect.
  2774. $html .= $value.'</option>';
  2775. }
  2776. $html .= '</select>';
  2777. $html .= '<noscript><input type="submit" name="user_select_language" value="'.get_lang('Ok').'" /></noscript>';
  2778. $html .= '</form>';
  2779. return $html;
  2780. }
  2781. /**
  2782. * Returns a list of all the languages that are made available by the admin.
  2783. * @return array An array with all languages. Structure of the array is
  2784. * array['name'] = An array with the name of every language
  2785. * array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  2786. */
  2787. function api_get_languages() {
  2788. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  2789. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  2790. $result = Database::query($sql);
  2791. $language_list = array();
  2792. while ($row = Database::fetch_array($result)) {
  2793. $language_list['name'][] = $row['original_name'];
  2794. $language_list['folder'][] = $row['dokeos_folder'];
  2795. }
  2796. return $language_list;
  2797. }
  2798. /**
  2799. * Returns the id (the database id) of a language
  2800. * @param string language name (the corresponding name of the language-folder in the filesystem)
  2801. * @return int id of the language
  2802. */
  2803. function api_get_language_id($language) {
  2804. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  2805. if (empty($language)) {
  2806. return null;
  2807. }
  2808. $language = Database::escape_string($language);
  2809. $sql = "SELECT id FROM $tbl_language WHERE available='1' AND dokeos_folder = '$language' LIMIT 1";
  2810. $result = Database::query($sql);
  2811. $row = Database::fetch_array($result);
  2812. return $row['id'];
  2813. }
  2814. /**
  2815. * Gets language of the requested type for the current user. Types are :
  2816. * user_profil_lang : profile language of current user
  2817. * user_select_lang : language selected by user at login
  2818. * course_lang : language of the current course
  2819. * platform_lang : default platform language
  2820. * @param string lang_type
  2821. * @param return language of the requested type or false if the language is not available
  2822. **/
  2823. function api_get_language_from_type($lang_type){
  2824. global $_user;
  2825. global $_course;
  2826. $toreturn = false;
  2827. switch ($lang_type) {
  2828. case 'platform_lang' :
  2829. $temp_lang = api_get_setting('platformLanguage');
  2830. if (!empty($temp_lang))
  2831. $toreturn = $temp_lang;
  2832. break;
  2833. case 'user_profil_lang' :
  2834. if (isset($_user['language']) && !empty($_user['language']) )
  2835. $toreturn = $_user['language'];
  2836. break;
  2837. case 'user_selected_lang' :
  2838. if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice']) )
  2839. $toreturn = ($_SESSION['user_language_choice']);
  2840. break;
  2841. case 'course_lang' :
  2842. if ($_course['language'] && !empty($_course['language']) )
  2843. $toreturn = $_course['language'];
  2844. break;
  2845. default :
  2846. $toreturn = false;
  2847. break;
  2848. }
  2849. return $toreturn;
  2850. }
  2851. function api_get_language_info($language_id) {
  2852. $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
  2853. $sql = 'SELECT * FROM '.$tbl_admin_languages.' WHERE id = "'.intval($language_id).'"';
  2854. $rs = Database::query($sql);
  2855. $language_info = array();
  2856. if (Database::num_rows($rs)) {
  2857. $language_info = Database::fetch_array($rs,'ASSOC');
  2858. }
  2859. return $language_info;
  2860. }
  2861. /**
  2862. * Returns the name of the visual (CSS) theme to be applied on the current page.
  2863. * The returned name depends on the platform, course or user -wide settings.
  2864. * @return string The visual theme's name, it is the name of a folder inside .../chamilo/main/css/
  2865. */
  2866. function api_get_visual_theme() {
  2867. static $visual_theme;
  2868. if (!isset($visual_theme)) {
  2869. $platform_theme = api_get_setting('stylesheets'); // Plataform's theme.
  2870. $visual_theme = $platform_theme;
  2871. if (api_get_setting('user_selected_theme') == 'true') {
  2872. $user_info = api_get_user_info();
  2873. $user_theme = $user_info['theme'];
  2874. if (!empty($user_theme)) {
  2875. $visual_theme = $user_theme; // User's theme.
  2876. }
  2877. }
  2878. $course_id = api_get_course_id();
  2879. if (!empty($course_id) && $course_id != -1) {
  2880. if (api_get_setting('allow_course_theme') == 'true') {
  2881. $course_theme = api_get_course_setting('course_theme');
  2882. if (!empty($course_theme) && $course_theme != -1) {
  2883. if (!empty($course_theme)) {
  2884. $visual_theme = $course_theme; // Course's theme.
  2885. }
  2886. }
  2887. $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
  2888. if ($allow_lp_theme == 1) {
  2889. global $lp_theme_css, $lp_theme_config; // These variables come from the file lp_controller.php.
  2890. if (!$lp_theme_config) {
  2891. if (!empty($lp_theme_css)) {
  2892. $visual_theme = $lp_theme_css; // LP's theme.
  2893. }
  2894. }
  2895. }
  2896. }
  2897. }
  2898. if (empty($visual_theme)) {
  2899. $visual_theme = 'chamilo';
  2900. }
  2901. global $lp_theme_log;
  2902. if ($lp_theme_log) {
  2903. $visual_theme = $platform_theme;
  2904. }
  2905. }
  2906. return $visual_theme;
  2907. }
  2908. /**
  2909. * Returns a list of CSS themes currently available in the CSS folder
  2910. * @return array List of themes directories from the css folder
  2911. * Note: Directory names (names of themes) in the file system should contain ASCII-characters only.
  2912. */
  2913. function api_get_themes() {
  2914. $cssdir = api_get_path(SYS_PATH).'main/css/';
  2915. $list_dir = array();
  2916. $list_name = array();
  2917. if (@is_dir($cssdir)) {
  2918. $themes = @scandir($cssdir);
  2919. if (is_array($themes)) {
  2920. if ($themes !== false) {
  2921. sort($themes);
  2922. foreach ($themes as & $theme) {
  2923. if (substr($theme, 0, 1) == '.') {
  2924. continue;
  2925. } else {
  2926. if (@is_dir($cssdir.$theme)) {
  2927. $list_dir[] = $theme;
  2928. $list_name[] = ucwords(str_replace('_', ' ', $theme));
  2929. }
  2930. }
  2931. }
  2932. }
  2933. }
  2934. }
  2935. return array($list_dir, $list_name);
  2936. }
  2937. /* WYSIWYG EDITOR
  2938. Functions for the WYSIWYG html editor.
  2939. Please, try to avoid using the following two functions. The preferable way to put
  2940. an editor's instance on a page is through using a FormValidator's class method. */
  2941. /**
  2942. * Displays the WYSIWYG editor for online editing of html
  2943. * @param string $name The name of the form-element
  2944. * @param string $content The default content of the html-editor
  2945. * @param int $height The height of the form element
  2946. * @param int $width The width of the form element
  2947. * @param string $attributes (optional) attributes for the form element
  2948. * @param array $editor_config (optional) Configuration options for the html-editor
  2949. */
  2950. function api_disp_html_area($name, $content = '', $height = '', $width = '100%', $attributes = null, $editor_config = null) {
  2951. global $_configuration, $_course, $fck_attribute;
  2952. require_once api_get_path(LIBRARY_PATH).'formvalidator/Element/html_editor.php';
  2953. $editor = new HTML_QuickForm_html_editor($name, null, $attributes, $editor_config);
  2954. $editor->setValue($content);
  2955. // The global variable $fck_attribute has been deprecated. It stays here for supporting old external code.
  2956. if( $height != '') {
  2957. $fck_attribute['Height'] = $height;
  2958. }
  2959. if( $width != '') {
  2960. $fck_attribute['Width'] = $width;
  2961. }
  2962. echo $editor->toHtml();
  2963. }
  2964. /**
  2965. * Returns generated html for showing the WYSIWYG editor on the page
  2966. * @param string $name The name of the form-element
  2967. * @param string $content The default content of the html-editor
  2968. * @param int $height The height of the form element
  2969. * @param int $width The width of the form element
  2970. * @param string $attributes (optional) attributes for the form element
  2971. * @param array $editor_config (optional) Configuration options for the html-editor
  2972. */
  2973. function api_return_html_area($name, $content = '', $height = '', $width = '100%', $attributes = null, $editor_config = null) {
  2974. global $_configuration, $_course, $fck_attribute;
  2975. require_once api_get_path(LIBRARY_PATH).'formvalidator/Element/html_editor.php';
  2976. $editor = new HTML_QuickForm_html_editor($name, null, $attributes, $editor_config);
  2977. $editor->setValue($content);
  2978. // The global variable $fck_attribute has been deprecated. It stays here for supporting old external code.
  2979. if ($height != '') {
  2980. $fck_attribute['Height'] = $height;
  2981. }
  2982. if ($width != '') {
  2983. $fck_attribute['Width'] = $width;
  2984. }
  2985. return $editor->toHtml();
  2986. }
  2987. /**
  2988. * Find the largest sort value in a given user_course_category
  2989. * This function is used when we are moving a course to a different category
  2990. * and also when a user subscribes to courses (the new course is added at the end of the main category
  2991. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2992. * @param int $user_course_category: the id of the user_course_category
  2993. * @return int the value of the highest sort of the user_course_category
  2994. */
  2995. function api_max_sort_value($user_course_category, $user_id) {
  2996. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2997. $sql_max = "SELECT max(sort) as max_sort FROM $tbl_course_user WHERE user_id='".intval($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND user_course_cat='".Database::escape_string($user_course_category)."'";
  2998. $result_max = Database::query($sql_max);
  2999. if (Database::num_rows($result_max) == 1) {
  3000. $row_max = Database::fetch_array($result_max);
  3001. return $row_max['max_sort'];
  3002. }
  3003. return 0;
  3004. }
  3005. /**
  3006. * This function converts the string "true" or "false" to a boolean true or false.
  3007. * This function is in the first place written for the Chamilo Config Settings (also named AWACS)
  3008. * @param string "true" or "false"
  3009. * @return boolean true or false
  3010. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3011. */
  3012. function string_2_boolean($string) {
  3013. if ($string == 'true') {
  3014. return true;
  3015. }
  3016. if ($string == 'false') {
  3017. return false;
  3018. }
  3019. return false;
  3020. }
  3021. /**
  3022. * Determines the number of plugins installed for a given location
  3023. */
  3024. function api_number_of_plugins($location) {
  3025. global $_plugins;
  3026. return isset($_plugins[$location]) && is_array($_plugins[$location]) ? count($_plugins[$location]) : 0;
  3027. }
  3028. /**
  3029. * Including the necessary plugins.
  3030. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3031. * @deprecated use AppPlugin::get_all_plugin_contents_by_block function
  3032. */
  3033. function api_plugin($location) {
  3034. global $_plugins;
  3035. if (isset($_plugins[$location]) && is_array($_plugins[$location])) {
  3036. foreach ($_plugins[$location] as $this_plugin) {
  3037. include api_get_path(SYS_PLUGIN_PATH)."$this_plugin/index.php";
  3038. }
  3039. }
  3040. return false;
  3041. }
  3042. /**
  3043. * Checks to see wether a certain plugin is installed.
  3044. * @return boolean true if the plugin is installed, false otherwise.
  3045. */
  3046. function api_is_plugin_installed($plugin_list, $plugin_name) {
  3047. if (is_array($plugin_list)) {
  3048. foreach ($plugin_list as $plugin_location) {
  3049. if (array_search($plugin_name, $plugin_location) !== false) { return true; }
  3050. }
  3051. }
  3052. return false;
  3053. }
  3054. /**
  3055. * Transforms a number of seconds in hh:mm:ss format
  3056. * @author Julian Prud'homme
  3057. * @param integer the number of seconds
  3058. * @return string the formated time
  3059. */
  3060. function api_time_to_hms($seconds) {
  3061. // $seconds = -1 means that we have wrong data in the db.
  3062. if ($seconds == -1) {
  3063. return get_lang('Unknown').Display::return_icon('info2.gif', get_lang('WrongDatasForTimeSpentOnThePlatform'), array('align' => 'absmiddle', 'hspace' => '3px'));
  3064. }
  3065. // How many hours ?
  3066. $hours = floor($seconds / 3600);
  3067. // How many minutes ?
  3068. $min = floor(($seconds - ($hours * 3600)) / 60);
  3069. // How many seconds
  3070. $sec = floor($seconds - ($hours * 3600) - ($min * 60));
  3071. if ($sec < 10) {
  3072. $sec = "0$sec";
  3073. }
  3074. if ($min < 10) {
  3075. $min = "0$min";
  3076. }
  3077. return "$hours:$min:$sec";
  3078. }
  3079. /* FILE SYSTEM RELATED FUNCTIONS */
  3080. /**
  3081. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3082. * The returnd value is based on the platform administrator's setting "Administration > Configuration settings > Security > Permissions for new directories".
  3083. * @return int Returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3084. */
  3085. function api_get_permissions_for_new_directories() {
  3086. static $permissions;
  3087. if (!isset($permissions)) {
  3088. $permissions = trim(api_get_setting('permissions_for_new_directories'));
  3089. // The default value 0777 is according to that in the platform administration panel after fresh system installation.
  3090. $permissions = octdec(!empty($permissions) ? $permissions : '0777');
  3091. }
  3092. return $permissions;
  3093. }
  3094. /**
  3095. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3096. * The returnd value is based on the platform administrator's setting "Administration > Configuration settings > Security > Permissions for new files".
  3097. * @return int Returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3098. */
  3099. function api_get_permissions_for_new_files() {
  3100. static $permissions;
  3101. if (!isset($permissions)) {
  3102. $permissions = trim(api_get_setting('permissions_for_new_files'));
  3103. // The default value 0666 is according to that in the platform administration panel after fresh system installation.
  3104. $permissions = octdec(!empty($permissions) ? $permissions : '0666');
  3105. }
  3106. return $permissions;
  3107. }
  3108. /**
  3109. * sys_get_temp_dir() was introduced as of PHP 5.2.1
  3110. * For older PHP versions the following implementation is to be activated.
  3111. * @link Based on http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/2/
  3112. */
  3113. if (!function_exists('sys_get_temp_dir')) {
  3114. function sys_get_temp_dir() {
  3115. // Try to get from environment variable.
  3116. if (!empty($_ENV['TMP'])) {
  3117. return realpath($_ENV['TMP']);
  3118. }
  3119. if (!empty($_ENV['TMPDIR'])) {
  3120. return realpath($_ENV['TMPDIR']);
  3121. }
  3122. if (!empty($_ENV['TEMP'])) {
  3123. return realpath($_ENV['TEMP']);
  3124. }
  3125. // Detect by creating a temporary file.
  3126. // Try to use system's temporary directory
  3127. // as random name shouldn't exist.
  3128. $temp_file = tempnam(md5(uniqid(rand(), true)), '');
  3129. if ($temp_file) {
  3130. $temp_dir = realpath(dirname($temp_file));
  3131. @unlink( $temp_file );
  3132. return $temp_dir;
  3133. }
  3134. return false;
  3135. }
  3136. }
  3137. /**
  3138. * Deletes a file, or a folder and its contents
  3139. *
  3140. * @author Aidan Lister <aidan@php.net>
  3141. * @version 1.0.3
  3142. * @param string $dirname Directory to delete
  3143. * @param bool Deletes only the content or not
  3144. * @return bool Returns TRUE on success, FALSE on failure
  3145. * @link http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  3146. * @author Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  3147. * @author Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  3148. */
  3149. function rmdirr($dirname, $delete_only_content_in_folder = false) {
  3150. $res = true;
  3151. // A sanity check.
  3152. if (!file_exists($dirname)) {
  3153. return false;
  3154. }
  3155. $php_errormsg = '';
  3156. // Simple delete for a file.
  3157. if (is_file($dirname) || is_link($dirname)) {
  3158. $res = unlink($dirname);
  3159. if ($res === false) {
  3160. error_log(__FILE__.' line '.__LINE__.': '.((bool)ini_get('track_errors') ? $php_errormsg : 'Error not recorded because track_errors is off in your php.ini'), 0);
  3161. }
  3162. return $res;
  3163. }
  3164. // Loop through the folder.
  3165. $dir = dir($dirname);
  3166. // A sanity check.
  3167. $is_object_dir = is_object($dir);
  3168. if ($is_object_dir) {
  3169. while (false !== $entry = $dir->read()) {
  3170. // Skip pointers.
  3171. if ($entry == '.' || $entry == '..') {
  3172. continue;
  3173. }
  3174. // Recurse.
  3175. rmdirr("$dirname/$entry");
  3176. }
  3177. }
  3178. // Clean up.
  3179. if ($is_object_dir) {
  3180. $dir->close();
  3181. }
  3182. if ($delete_only_content_in_folder == false) {
  3183. $res = rmdir($dirname);
  3184. if ($res === false) {
  3185. error_log(__FILE__.' line '.__LINE__.': '.((bool)ini_get('track_errors') ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
  3186. }
  3187. }
  3188. return $res;
  3189. }
  3190. // TODO: This function is to be simplified. File access modes to be implemented.
  3191. /**
  3192. * function adapted from a php.net comment
  3193. * copy recursively a folder
  3194. * @param the source folder
  3195. * @param the dest folder
  3196. * @param an array of excluded file_name (without extension)
  3197. * @param copied_files the returned array of copied files
  3198. */
  3199. function copyr($source, $dest, $exclude = array(), $copied_files = array()) {
  3200. if (empty($dest)) { return false; }
  3201. // Simple copy for a file
  3202. if (is_file($source)) {
  3203. $path_info = pathinfo($source);
  3204. if (!in_array($path_info['filename'], $exclude)) {
  3205. copy($source, $dest);
  3206. }
  3207. return true;
  3208. } elseif (!is_dir($source)) {
  3209. //then source is not a dir nor a file, return
  3210. return false;
  3211. }
  3212. // Make destination directory.
  3213. if (!is_dir($dest)) {
  3214. mkdir($dest, api_get_permissions_for_new_directories());
  3215. }
  3216. // Loop through the folder.
  3217. $dir = dir($source);
  3218. while (false !== $entry = $dir->read()) {
  3219. // Skip pointers
  3220. if ($entry == '.' || $entry == '..') {
  3221. continue;
  3222. }
  3223. // Deep copy directories.
  3224. if ($dest !== "$source/$entry") {
  3225. $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
  3226. }
  3227. }
  3228. // Clean up.
  3229. $dir->close();
  3230. return true;
  3231. }
  3232. // TODO: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach. Documentation header to be added here.
  3233. function copy_folder_course_session($pathname, $base_path_document, $session_id, $course_info, $document, $source_course_id) {
  3234. $table = Database :: get_course_table(TABLE_DOCUMENT);
  3235. $session_id = intval($session_id);
  3236. $source_course_id = intval($source_course_id);
  3237. // Check whether directory already exists.
  3238. if (is_dir($pathname) || empty($pathname)) {
  3239. return true;
  3240. }
  3241. // Ensure that a file with the same name does not already exist.
  3242. if (is_file($pathname)) {
  3243. trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
  3244. return false;
  3245. }
  3246. $course_id = $course_info['real_id'];
  3247. $folders = explode(DIRECTORY_SEPARATOR,str_replace($base_path_document.DIRECTORY_SEPARATOR,'',$pathname));
  3248. $new_pathname = $base_path_document;
  3249. $path = '';
  3250. foreach ($folders as $folder) {
  3251. $new_pathname .= DIRECTORY_SEPARATOR.$folder;
  3252. $path .= DIRECTORY_SEPARATOR.$folder;
  3253. if (!file_exists($new_pathname)) {
  3254. $path = Database::escape_string($path);
  3255. $sql = "SELECT * FROM $table WHERE c_id = $source_course_id AND path = '$path' AND filetype = 'folder' AND session_id = '$session_id'";
  3256. $rs1 = Database::query($sql);
  3257. $num_rows = Database::num_rows($rs1);
  3258. if ($num_rows == 0) {
  3259. mkdir($new_pathname, api_get_permissions_for_new_directories());
  3260. // Insert new folder with destination session_id.
  3261. $sql = "INSERT INTO ".$table." SET
  3262. c_id = $course_id,
  3263. path = '$path',
  3264. comment = '".Database::escape_string($document->comment)."',
  3265. title = '".Database::escape_string(basename($new_pathname))."' ,
  3266. filetype='folder',
  3267. size= '0',
  3268. session_id = '$session_id'";
  3269. Database::query($sql);
  3270. $document_id = Database::insert_id();
  3271. api_item_property_update($course_info,TOOL_DOCUMENT,$document_id,'FolderCreated',api_get_user_id(),0,0,null,null,$session_id);
  3272. }
  3273. }
  3274. } // en foreach
  3275. }
  3276. // TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
  3277. function api_chmod_R($path, $filemode) {
  3278. if (!is_dir($path)) {
  3279. return chmod($path, $filemode);
  3280. }
  3281. $handler = opendir($path);
  3282. while ($file = readdir($handler)) {
  3283. if ($file != '.' && $file != '..') {
  3284. $fullpath = "$path/$file";
  3285. if (!is_dir($fullpath)) {
  3286. if (!chmod($fullpath, $filemode)) {
  3287. return false;
  3288. }
  3289. } else {
  3290. if (!api_chmod_R($fullpath, $filemode)) {
  3291. return false;
  3292. }
  3293. }
  3294. }
  3295. }
  3296. closedir($handler);
  3297. return chmod($path, $filemode);
  3298. }
  3299. // TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
  3300. /**
  3301. * Parse info file format. (e.g: file.info)
  3302. *
  3303. * Files should use an ini-like format to specify values.
  3304. * White-space generally doesn't matter, except inside values.
  3305. * e.g.
  3306. *
  3307. * @verbatim
  3308. * key = value
  3309. * key = "value"
  3310. * key = 'value'
  3311. * key = "multi-line
  3312. *
  3313. * value"
  3314. * key = 'multi-line
  3315. *
  3316. * value'
  3317. * key
  3318. * =
  3319. * 'value'
  3320. * @endverbatim
  3321. *
  3322. * Arrays are created using a GET-like syntax:
  3323. *
  3324. * @verbatim
  3325. * key[] = "numeric array"
  3326. * key[index] = "associative array"
  3327. * key[index][] = "nested numeric array"
  3328. * key[index][index] = "nested associative array"
  3329. * @endverbatim
  3330. *
  3331. * PHP constants are substituted in, but only when used as the entire value:
  3332. *
  3333. * Comments should start with a semi-colon at the beginning of a line.
  3334. *
  3335. * This function is NOT for placing arbitrary module-specific settings. Use
  3336. * variable_get() and variable_set() for that.
  3337. *
  3338. * Information stored in the module.info file:
  3339. * - name: The real name of the module for display purposes.
  3340. * - description: A brief description of the module.
  3341. * - dependencies: An array of shortnames of other modules this module depends on.
  3342. * - package: The name of the package of modules this module belongs to.
  3343. *
  3344. * Example of .info file:
  3345. * <code>
  3346. * @verbatim
  3347. * name = Forum
  3348. * description = Enables threaded discussions about general topics.
  3349. * dependencies[] = taxonomy
  3350. * dependencies[] = comment
  3351. * package = Core - optional
  3352. * version = VERSION
  3353. * @endverbatim
  3354. * </code>
  3355. * @param $filename
  3356. * The file we are parsing. Accepts file with relative or absolute path.
  3357. * @return
  3358. * The info array.
  3359. */
  3360. function parse_info_file($filename) {
  3361. $info = array();
  3362. if (!file_exists($filename)) {
  3363. return $info;
  3364. }
  3365. $data = file_get_contents($filename);
  3366. if (preg_match_all('
  3367. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  3368. ((?:
  3369. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  3370. \[[^\[\]]*\] # unless they are balanced and not nested
  3371. )+?)
  3372. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  3373. (?:
  3374. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  3375. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  3376. ([^\r\n]*?) # Non-quoted string
  3377. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  3378. @msx', $data, $matches, PREG_SET_ORDER)) {
  3379. $key = $value1 = $value2 = $value3 = '';
  3380. foreach ($matches as $match) {
  3381. // Fetch the key and value string.
  3382. $i = 0;
  3383. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  3384. $$var = isset($match[++$i]) ? $match[$i] : '';
  3385. }
  3386. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  3387. // Parse array syntax.
  3388. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  3389. $last = array_pop($keys);
  3390. $parent = &$info;
  3391. // Create nested arrays.
  3392. foreach ($keys as $key) {
  3393. if ($key == '') {
  3394. $key = count($parent);
  3395. }
  3396. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  3397. $parent[$key] = array();
  3398. }
  3399. $parent = &$parent[$key];
  3400. }
  3401. // Handle PHP constants.
  3402. if (defined($value)) {
  3403. $value = constant($value);
  3404. }
  3405. // Insert actual value.
  3406. if ($last == '') {
  3407. $last = count($parent);
  3408. }
  3409. $parent[$last] = $value;
  3410. }
  3411. }
  3412. return $info;
  3413. }
  3414. /**
  3415. * Gets Chamilo version from the configuration files
  3416. * @return string A string of type "1.8.4", or an empty string if the version could not be found
  3417. */
  3418. function api_get_version() {
  3419. global $_configuration;
  3420. return (string)$_configuration['system_version'];
  3421. }
  3422. /**
  3423. * Gets the software name (the name/brand of the Chamilo-based customized system)
  3424. * @return string
  3425. */
  3426. function api_get_software_name() {
  3427. global $_configuration;
  3428. if (isset($_configuration['software_name']) && !empty($_configuration['software_name'])) {
  3429. return $_configuration['software_name'];
  3430. } else {
  3431. return 'Chamilo';
  3432. }
  3433. }
  3434. /**
  3435. * Checks whether status given in parameter exists in the platform
  3436. * @param mixed the status (can be either int either string)
  3437. * @return true if the status exists, else returns false
  3438. */
  3439. function api_status_exists($status_asked) {
  3440. global $_status_list;
  3441. return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
  3442. }
  3443. /**
  3444. * Checks whether status given in parameter exists in the platform. The function
  3445. * returns the status ID or false if it does not exist, but given the fact there
  3446. * is no "0" status, the return value can be checked against
  3447. * if(api_status_key()) to know if it exists.
  3448. * @param mixed The status (can be either int or string)
  3449. * @return mixed Status ID if exists, false otherwise
  3450. */
  3451. function api_status_key($status) {
  3452. global $_status_list;
  3453. return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
  3454. }
  3455. /**
  3456. * Gets the status langvars list
  3457. * @return array the list of status with their translations
  3458. */
  3459. function api_get_status_langvars() {
  3460. return array(
  3461. COURSEMANAGER => get_lang('Teacher', ''),
  3462. SESSIONADMIN => get_lang('SessionsAdmin', ''),
  3463. DRH => get_lang('Drh', ''),
  3464. STUDENT => get_lang('Student', ''),
  3465. ANONYMOUS => get_lang('Anonymous', '')
  3466. );
  3467. }
  3468. /**
  3469. * The function that retrieves all the possible settings for a certain config setting
  3470. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3471. */
  3472. function api_get_settings_options($var) {
  3473. $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3474. $var = Database::escape_string($var);
  3475. $sql = "SELECT * FROM $table_settings_options WHERE variable = '$var' ORDER BY id";
  3476. $result = Database::query($sql);
  3477. $settings_options_array = array();
  3478. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3479. //$temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
  3480. $settings_options_array[] = $row;
  3481. }
  3482. return $settings_options_array;
  3483. }
  3484. function api_set_setting_option($params) {
  3485. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3486. if (empty($params['id'])) {
  3487. Database::insert($table, $params);
  3488. } else {
  3489. Database::update($table, $params, array('id = ? '=> $params['id']));
  3490. }
  3491. }
  3492. function api_delete_setting_option($id) {
  3493. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3494. if (!empty($id)) {
  3495. Database::delete($table, array('id = ? '=> $id));
  3496. }
  3497. }
  3498. /**
  3499. * Sets a platform configuration setting to a given value
  3500. * @param string The variable we want to update
  3501. * @param string The value we want to record
  3502. * @param string The sub-variable if any (in most cases, this will remain null)
  3503. * @param string The category if any (in most cases, this will remain null)
  3504. * @param int The access_url for which this parameter is valid
  3505. */
  3506. function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1) {
  3507. if (empty($var)) { return false; }
  3508. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3509. $var = Database::escape_string($var);
  3510. $value = Database::escape_string($value);
  3511. $access_url = (int)$access_url;
  3512. if (empty($access_url)) { $access_url = 1; }
  3513. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  3514. if (!empty($subvar)) {
  3515. $subvar = Database::escape_string($subvar);
  3516. $select .= " AND subkey = '$subvar'";
  3517. }
  3518. if (!empty($cat)) {
  3519. $cat = Database::escape_string($cat);
  3520. $select .= " AND category = '$cat'";
  3521. }
  3522. if ($access_url > 1) {
  3523. $select .= " AND access_url = $access_url";
  3524. } else {
  3525. $select .= " AND access_url = 1 ";
  3526. }
  3527. $res = Database::query($select);
  3528. if (Database::num_rows($res) > 0) {
  3529. // Found item for this access_url.
  3530. $row = Database::fetch_array($res);
  3531. $update = "UPDATE $t_settings SET selected_value = '$value' WHERE id = ".$row['id'] ;
  3532. $res = Database::query($update);
  3533. } else {
  3534. // Item not found for this access_url, we have to check if it exist with access_url = 1
  3535. $select = "SELECT * FROM $t_settings WHERE variable = '$var' AND access_url = 1 ";
  3536. // Just in case
  3537. if ($access_url == 1) {
  3538. if (!empty($subvar)) {
  3539. $select .= " AND subkey = '$subvar'";
  3540. }
  3541. if (!empty($cat)) {
  3542. $select .= " AND category = '$cat'";
  3543. }
  3544. $res = Database::query($select);
  3545. if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one.
  3546. $row = Database::fetch_array($res);
  3547. $insert = "INSERT INTO $t_settings " .
  3548. "(variable,subkey," .
  3549. "type,category," .
  3550. "selected_value,title," .
  3551. "comment,scope," .
  3552. "subkeytext,access_url)" .
  3553. " VALUES " .
  3554. "('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  3555. "'".$row['type']."','".$row['category']."'," .
  3556. "'$value','".$row['title']."'," .
  3557. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  3558. "".(!empty($row['subkeytext'])?"'".$row['subkeytext']."'":"NULL").",$access_url)";
  3559. $res = Database::query($insert);
  3560. } else { // Such a setting does not exist.
  3561. error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
  3562. }
  3563. } else {
  3564. // Other access url.
  3565. if (!empty($subvar)) {
  3566. $select .= " AND subkey = '$subvar'";
  3567. }
  3568. if (!empty($cat)) {
  3569. $select .= " AND category = '$cat'";
  3570. }
  3571. $res = Database::query($select);
  3572. if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one.
  3573. $row = Database::fetch_array($res);
  3574. if ($row['access_url_changeable'] == 1) {
  3575. $insert = "INSERT INTO $t_settings " .
  3576. "(variable,subkey," .
  3577. "type,category," .
  3578. "selected_value,title," .
  3579. "comment,scope," .
  3580. "subkeytext,access_url, access_url_changeable)" .
  3581. " VALUES " .
  3582. "('".$row['variable']."',".
  3583. (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  3584. "'".$row['type']."','".$row['category']."'," .
  3585. "'$value','".$row['title']."'," .
  3586. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
  3587. (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  3588. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
  3589. $res = Database::query($insert);
  3590. }
  3591. } else { // Such a setting does not exist.
  3592. error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
  3593. }
  3594. }
  3595. }
  3596. }
  3597. /**
  3598. * Sets a whole category of settings to one specific value
  3599. * @param string Category
  3600. * @param string Value
  3601. * @param int Access URL. Optional. Defaults to 1
  3602. * @param array Optional array of filters on field type
  3603. */
  3604. function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = array()) {
  3605. if (empty($category)) { return false; }
  3606. $category = Database::escape_string($category);
  3607. $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3608. $access_url = (int) $access_url;
  3609. if (empty($access_url)) { $access_url = 1; }
  3610. if (isset($value)) {
  3611. $value = Database::escape_string($value);
  3612. $sql = "UPDATE $t_s SET selected_value = '$value' WHERE category = '$category' AND access_url = $access_url";
  3613. if (is_array($fieldtype) && count($fieldtype)>0) {
  3614. $sql .= " AND ( ";
  3615. $i = 0;
  3616. foreach ($fieldtype as $type){
  3617. if ($i > 0) {
  3618. $sql .= ' OR ';
  3619. }
  3620. $type = Database::escape_string($type);
  3621. $sql .= " type='".$type."' ";
  3622. $i++;
  3623. }
  3624. $sql .= ")";
  3625. }
  3626. $res = Database::query($sql);
  3627. return $res !== false;
  3628. } else {
  3629. $sql = "UPDATE $t_s SET selected_value = NULL WHERE category = '$category' AND access_url = $access_url";
  3630. if (is_array($fieldtype) && count($fieldtype)>0) {
  3631. $sql .= " AND ( ";
  3632. $i = 0;
  3633. foreach ($fieldtype as $type){
  3634. if ($i > 0) {
  3635. $sql .= ' OR ';
  3636. }
  3637. $type = Database::escape_string($type);
  3638. $sql .= " type='".$type."' ";
  3639. $i++;
  3640. }
  3641. $sql .= ")";
  3642. }
  3643. $res = Database::query($sql);
  3644. return $res !== false;
  3645. }
  3646. }
  3647. /**
  3648. * Gets all available access urls in an array (as in the database)
  3649. * @return array An array of database records
  3650. */
  3651. function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC') {
  3652. $t_au = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3653. $from = (int) $from;
  3654. $to = (int) $to;
  3655. $order = Database::escape_string($order);
  3656. $direction = Database::escape_string($direction);
  3657. $sql = "SELECT id, url, description, active, created_by, tms FROM $t_au ORDER BY $order $direction LIMIT $to OFFSET $from";
  3658. $res = Database::query($sql);
  3659. return Database::store_result($res);
  3660. }
  3661. /**
  3662. * Gets the access url info in an array
  3663. * @param id of the access url
  3664. * @return array Array with all the info (url, description, active, created_by, tms) from the access_url table
  3665. * @author Julio Montoya Armas
  3666. */
  3667. function api_get_access_url($id) {
  3668. global $_configuration;
  3669. $id = Database::escape_string(intval($id));
  3670. // Calling the Database:: library dont work this is handmade.
  3671. //$table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3672. $table = 'access_url';
  3673. $database = $_configuration['main_database'];
  3674. $table_access_url = "".$database.".".$table."";
  3675. $sql = "SELECT url, description, active, created_by, tms
  3676. FROM $table_access_url WHERE id = '$id' ";
  3677. $res = Database::query($sql);
  3678. $result = @Database::fetch_array($res);
  3679. return $result;
  3680. }
  3681. /**
  3682. * Adds an access URL into the database
  3683. * @param string URL
  3684. * @param string Description
  3685. * @param int Active (1= active, 0=disabled)
  3686. * @return int The new database id, or the existing database id if this url already exists
  3687. */
  3688. function api_add_access_url($u, $d = '', $a = 1) {
  3689. $t_au = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3690. $u = Database::escape_string($u);
  3691. $d = Database::escape_string($d);
  3692. $a = (int) $a;
  3693. $sql = "SELECT id FROM $t_au WHERE url LIKE '$u'";
  3694. $res = Database::query($sql);
  3695. if ($res === false) {
  3696. // Problem querying the database - return false.
  3697. return false;
  3698. }
  3699. if (Database::num_rows($res) > 0) {
  3700. return Database::result($res, 0, 'id');
  3701. }
  3702. $ui = api_get_user_id();
  3703. $sql = "INSERT INTO $t_au (url,description,active,created_by,tms) VALUES ('$u','$d',$a,$ui,'')";
  3704. $res = Database::query($sql);
  3705. return ($res === false) ? false : Database::insert_id();
  3706. }
  3707. /**
  3708. * Gets all the current settings for a specific access url
  3709. * @param string The category, if any, that we want to get
  3710. * @param string Whether we want a simple list (display a catgeory) or a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
  3711. * @param int Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  3712. * @return array Array of database results for the current settings of the current access URL
  3713. */
  3714. function & api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0) {
  3715. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3716. $access_url = (int) $access_url;
  3717. $where_condition = '';
  3718. if ($url_changeable == 1) {
  3719. $where_condition = " AND access_url_changeable= '1' ";
  3720. }
  3721. if (empty($access_url) or $access_url == -1) { $access_url = 1; }
  3722. $sql = "SELECT id, variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable " .
  3723. " FROM $t_cs WHERE access_url = $access_url $where_condition ";
  3724. if (!empty($cat)) {
  3725. $cat = Database::escape_string($cat);
  3726. $sql .= " AND category='$cat' ";
  3727. }
  3728. if ($ordering == 'group') {
  3729. $sql .= " GROUP BY variable ORDER BY id ASC";
  3730. } else {
  3731. $sql .= " ORDER BY 1,2 ASC";
  3732. }
  3733. $result = Database::store_result(Database::query($sql));
  3734. return $result;
  3735. }
  3736. /**
  3737. * Gets the distinct settings categories
  3738. * @param array Array of strings giving the categories we want to exclude
  3739. * @param int Access URL. Optional. Defaults to 1
  3740. * @return array A list of categories
  3741. */
  3742. function & api_get_settings_categories($exceptions = array(), $access_url = 1) {
  3743. $access_url = (int) $access_url;
  3744. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3745. $list = "'".implode("','",$exceptions)."'";
  3746. $sql = "SELECT DISTINCT category FROM $t_cs";
  3747. if ($list != "'',''" and $list != "''" and !empty($list)) {
  3748. $sql .= " WHERE category NOT IN ($list)";
  3749. }
  3750. $result = Database::store_result(Database::query($sql));
  3751. return $result;
  3752. }
  3753. /**
  3754. * Deletes a setting
  3755. * @param string Variable
  3756. * @param string Subkey
  3757. * @param int Access URL
  3758. * @return boolean False on failure, true on success
  3759. */
  3760. function api_delete_setting($v, $s = null, $a = 1) {
  3761. if (empty($v)) { return false; }
  3762. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3763. $v = Database::escape_string($v);
  3764. $a = (int) $a;
  3765. if (empty($a)) { $a = 1; }
  3766. if (!empty($s)) {
  3767. $s = Database::escape_string($s);
  3768. $sql = "DELETE FROM $t_cs WHERE variable = '$v' AND subkey = '$s' AND access_url = $a";
  3769. $r = Database::query($sql);
  3770. return $r;
  3771. }
  3772. $sql = "DELETE FROM $t_cs WHERE variable = '$v' AND access_url = $a";
  3773. $r = Database::query($sql);
  3774. return $r;
  3775. }
  3776. /**
  3777. * Deletes all the settings from one category
  3778. * @param string Subkey
  3779. * @param int Access URL
  3780. * @return boolean False on failure, true on success
  3781. */
  3782. function api_delete_category_settings_by_subkey($subkey, $access_url_id = 1) {
  3783. if (empty($subkey)) { return false; }
  3784. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3785. $subkey = Database::escape_string($subkey);
  3786. $access_url_id = intval($access_url_id);
  3787. $sql = "DELETE FROM $t_cs WHERE subkey = '$subkey' AND access_url = $access_url_id";
  3788. $r = Database::query($sql);
  3789. return $r;
  3790. }
  3791. /**
  3792. * Sets a platform configuration setting to a given value
  3793. * @param string The value we want to record
  3794. * @param string The variable name we want to insert
  3795. * @param string The subkey for the variable we want to insert
  3796. * @param string The type for the variable we want to insert
  3797. * @param string The category for the variable we want to insert
  3798. * @param string The title
  3799. * @param string The comment
  3800. * @param string The scope
  3801. * @param string The subkey text
  3802. * @param int The access_url for which this parameter is valid
  3803. * @param int The changeability of this setting for non-master urls
  3804. * @return boolean true on success, false on failure
  3805. */
  3806. function api_add_setting($val, $var, $sk = null, $type = 'textfield', $c = null, $title = '', $com = '', $sc = null, $skt = null, $a = 1, $v = 0) {
  3807. if (empty($var) || !isset($val)) { return false; }
  3808. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3809. $var = Database::escape_string($var);
  3810. $val = Database::escape_string($val);
  3811. $a = (int) $a;
  3812. if (empty($a)) { $a = 1; }
  3813. // Check if this variable doesn't exist already
  3814. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  3815. if (!empty($sk)) {
  3816. $sk = Database::escape_string($sk);
  3817. $select .= " AND subkey = '$sk'";
  3818. }
  3819. if ($a > 1) {
  3820. $select .= " AND access_url = $a";
  3821. } else {
  3822. $select .= " AND access_url = 1 ";
  3823. }
  3824. $res = Database::query($select);
  3825. if (Database::num_rows($res) > 0) { // Found item for this access_url.
  3826. $row = Database::fetch_array($res);
  3827. return $row['id'];
  3828. }
  3829. // Item not found for this access_url, we have to check if the whole thing is missing
  3830. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  3831. $insert = "INSERT INTO $t_settings " .
  3832. "(variable,selected_value," .
  3833. "type,category," .
  3834. "subkey,title," .
  3835. "comment,scope," .
  3836. "subkeytext,access_url,access_url_changeable)" .
  3837. " VALUES ('$var','$val',";
  3838. if (isset($type)) {
  3839. $type = Database::escape_string($type);
  3840. $insert .= "'$type',";
  3841. } else {
  3842. $insert .= "NULL,";
  3843. }
  3844. if (isset($c)) { // Category
  3845. $c = Database::escape_string($c);
  3846. $insert .= "'$c',";
  3847. } else {
  3848. $insert .= "NULL,";
  3849. }
  3850. if (isset($sk)) { // Subkey
  3851. $sk = Database::escape_string($sk);
  3852. $insert .= "'$sk',";
  3853. } else {
  3854. $insert .= "NULL,";
  3855. }
  3856. if (isset($title)) { // Title
  3857. $title = Database::escape_string($title);
  3858. $insert .= "'$title',";
  3859. } else {
  3860. $insert .= "NULL,";
  3861. }
  3862. if (isset($com)) { // Comment
  3863. $com = Database::escape_string($com);
  3864. $insert .= "'$com',";
  3865. } else {
  3866. $insert .= "NULL,";
  3867. }
  3868. if (isset($sc)) { // Scope
  3869. $sc = Database::escape_string($sc);
  3870. $insert .= "'$sc',";
  3871. } else {
  3872. $insert .= "NULL,";
  3873. }
  3874. if (isset($skt)) { // Subkey text
  3875. $skt = Database::escape_string($skt);
  3876. $insert .= "'$skt',";
  3877. } else {
  3878. $insert .= "NULL,";
  3879. }
  3880. $insert .= "$a,$v)";
  3881. $res = Database::query($insert);
  3882. return $res;
  3883. }
  3884. /**
  3885. * Checks wether a user can or can't view the contents of a course.
  3886. *
  3887. * @param int $userid User id or NULL to get it from $_SESSION
  3888. * @param int $cid Course id to check whether the user is allowed.
  3889. * @return bool
  3890. */
  3891. function api_is_course_visible_for_user($userid = null, $cid = null) {
  3892. if ($userid == null) {
  3893. $userid = api_get_user_id();
  3894. }
  3895. if (empty($userid) || strval(intval($userid)) != $userid) {
  3896. if (api_is_anonymous()) {
  3897. $userid = api_get_anonymous_id();
  3898. } else {
  3899. return false;
  3900. }
  3901. }
  3902. $cid = Database::escape_string($cid);
  3903. global $is_platformAdmin;
  3904. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  3905. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  3906. $sql = "SELECT
  3907. $course_table.category_code,
  3908. $course_table.visibility,
  3909. $course_table.code,
  3910. $course_cat_table.code
  3911. FROM $course_table
  3912. LEFT JOIN $course_cat_table
  3913. ON $course_table.category_code = $course_cat_table.code
  3914. WHERE
  3915. $course_table.code = '$cid'
  3916. LIMIT 1";
  3917. $result = Database::query($sql);
  3918. if (Database::num_rows($result) > 0) {
  3919. $visibility = Database::fetch_array($result);
  3920. $visibility = $visibility['visibility'];
  3921. } else {
  3922. $visibility = 0;
  3923. }
  3924. // Shortcut permissions in case the visibility is "open to the world".
  3925. if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
  3926. return true;
  3927. }
  3928. if (api_get_setting('use_session_mode') != 'true') {
  3929. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3930. $sql = "SELECT tutor_id, status
  3931. FROM $course_user_table
  3932. WHERE user_id = '$userid' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."
  3933. AND course_code = '$cid'
  3934. LIMIT 1";
  3935. $result = Database::query($sql);
  3936. if (Database::num_rows($result) > 0) {
  3937. // This user have a recorded state for this course.
  3938. $cuData = Database::fetch_array($result);
  3939. $is_courseMember = true;
  3940. $is_courseTutor = ($cuData['tutor_id' ] == 1);
  3941. $is_courseAdmin = ($cuData['status'] == 1);
  3942. } else {
  3943. // This user has no status related to this course.
  3944. $is_courseMember = false;
  3945. $is_courseAdmin = false;
  3946. $is_courseTutor = false;
  3947. }
  3948. $is_courseAdmin = ($is_courseAdmin || $is_platformAdmin);
  3949. } else {
  3950. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3951. $sql = "SELECT
  3952. tutor_id, status, role
  3953. FROM $tbl_course_user
  3954. WHERE
  3955. user_id = '$userid'
  3956. AND
  3957. relation_type <> '".COURSE_RELATION_TYPE_RRHH."'
  3958. AND
  3959. course_code = '$cid'
  3960. LIMIT 1";
  3961. $result = Database::query($sql);
  3962. if (Database::num_rows($result) > 0) {
  3963. // This user has got a recorded state for this course.
  3964. $cuData = Database::fetch_array($result);
  3965. $_courseUser['role'] = $cuData['role'];
  3966. $is_courseMember = true;
  3967. $is_courseTutor = ($cuData['tutor_id' ] == 1);
  3968. $is_courseAdmin = ($cuData['status'] == 1);
  3969. }
  3970. if (!$is_courseAdmin) {
  3971. // This user has no status related to this course.
  3972. // Is it the session coach or the session admin?
  3973. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3974. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3975. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3976. $sql = "SELECT
  3977. session.id_coach, session_admin_id, session.id
  3978. FROM
  3979. $tbl_session as session
  3980. INNER JOIN $tbl_session_course
  3981. ON session_rel_course.id_session = session.id
  3982. AND session_rel_course.course_code = '$cid'
  3983. LIMIT 1";
  3984. $result = Database::query($sql);
  3985. $row = Database::store_result($result);
  3986. if ($row[0]['id_coach'] == $userid) {
  3987. $_courseUser['role'] = 'Professor';
  3988. $is_courseMember = true;
  3989. $is_courseTutor = true;
  3990. $is_courseAdmin = false;
  3991. $is_courseCoach = true;
  3992. $is_sessionAdmin = false;
  3993. api_session_register('_courseUser');
  3994. }
  3995. elseif ($row[0]['session_admin_id'] == $userid) {
  3996. $_courseUser['role'] = 'Professor';
  3997. $is_courseMember = false;
  3998. $is_courseTutor = false;
  3999. $is_courseAdmin = false;
  4000. $is_courseCoach = false;
  4001. $is_sessionAdmin = true;
  4002. } else {
  4003. // Check if the current user is the course coach.
  4004. $sql = "SELECT 1
  4005. FROM $tbl_session_course
  4006. WHERE session_rel_course.course_code = '$cid'
  4007. AND session_rel_course.id_coach = '$userid'
  4008. LIMIT 1";
  4009. $result = Database::query($sql);
  4010. //if ($row = Database::fetch_array($result)) {
  4011. if (Database::num_rows($result) > 0 ) {
  4012. $_courseUser['role'] = 'Professor';
  4013. $is_courseMember = true;
  4014. $is_courseTutor = true;
  4015. $is_courseCoach = true;
  4016. $is_sessionAdmin = false;
  4017. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  4018. $sql = "SELECT status FROM $tbl_user
  4019. WHERE user_id = $userid LIMIT 1";
  4020. $result = Database::query($sql);
  4021. if (Database::result($result, 0, 0) == 1) {
  4022. $is_courseAdmin = true;
  4023. } else {
  4024. $is_courseAdmin = false;
  4025. }
  4026. } else {
  4027. // Check if the user is a student is this session.
  4028. $sql = "SELECT id
  4029. FROM $tbl_session_course_user
  4030. WHERE id_user = '$userid'
  4031. AND course_code = '$cid'
  4032. LIMIT 1";
  4033. if (Database::num_rows($result) > 0) {
  4034. // This user haa got a recorded state for this course.
  4035. while ($row = Database::fetch_array($result)) {
  4036. $is_courseMember = true;
  4037. $is_courseTutor = false;
  4038. $is_courseAdmin = false;
  4039. $is_sessionAdmin = false;
  4040. }
  4041. }
  4042. }
  4043. }
  4044. }
  4045. }
  4046. switch ($visibility) {
  4047. case COURSE_VISIBILITY_OPEN_WORLD:
  4048. return true;
  4049. case COURSE_VISIBILITY_OPEN_PLATFORM:
  4050. return isset($userid);
  4051. case COURSE_VISIBILITY_REGISTERED:
  4052. case COURSE_VISIBILITY_CLOSED:
  4053. return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
  4054. }
  4055. return false;
  4056. }
  4057. /**
  4058. * Returns whether an element (forum, message, survey ...) belongs to a session or not
  4059. * @param String the tool of the element
  4060. * @param int the element id in database
  4061. * @param int the session_id to compare with element session id
  4062. * @return boolean true if the element is in the session, false else
  4063. */
  4064. function api_is_element_in_the_session($tool, $element_id, $session_id = null) {
  4065. if (is_null($session_id)) {
  4066. $session_id = intval($_SESSION['id_session']);
  4067. }
  4068. // Get information to build query depending of the tool.
  4069. switch ($tool) {
  4070. case TOOL_SURVEY :
  4071. $table_tool = Database::get_course_table(TABLE_SURVEY);
  4072. $key_field = 'survey_id';
  4073. break;
  4074. case TOOL_ANNOUNCEMENT :
  4075. $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
  4076. $key_field = 'id';
  4077. break;
  4078. case TOOL_AGENDA :
  4079. $table_tool = Database::get_course_table(TABLE_AGENDA);
  4080. $key_field = 'id';
  4081. break;
  4082. case TOOL_GROUP :
  4083. $table_tool = Database::get_course_table(TABLE_GROUP);
  4084. $key_field = 'id';
  4085. break;
  4086. default: return false;
  4087. }
  4088. $course_id = api_get_course_int_id();
  4089. $sql = "SELECT session_id FROM $table_tool WHERE c_id = $course_id AND $key_field = ".intval($element_id);
  4090. $rs = Database::query($sql);
  4091. if ($element_session_id = Database::result($rs, 0, 0)) {
  4092. if ($element_session_id == intval($session_id)) { // The element belongs to the session.
  4093. return true;
  4094. }
  4095. }
  4096. return false;
  4097. }
  4098. /**
  4099. * Replaces "forbidden" characters in a filename string.
  4100. *
  4101. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  4102. * @author René Haentjens, UGent (RH)
  4103. * @author Ivan Tcholakov, JUN-2009. Transliteration functionality has been added.
  4104. * @param string $filename The filename string.
  4105. * @param string $strict (optional) When it is 'strict', all non-ASCII charaters will be replaced. Additional ASCII replacemets will be done too.
  4106. * @return string The cleaned filename.
  4107. */
  4108. function replace_dangerous_char($filename, $strict = 'loose') {
  4109. // Safe replacements for some non-letter characters.
  4110. static $search = array("\0", ' ', "\t", "\n", "\r", "\x0B", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%');
  4111. static $replace = array('', '_', '_', '_', '_', '_', '-', '-', '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-');
  4112. // Encoding detection.
  4113. $encoding = api_detect_encoding($filename);
  4114. // Converting html-entities into encoded characters.
  4115. $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
  4116. // Transliteration to ASCII letters, they are not dangerous for filesystems.
  4117. $filename = api_transliterate($filename, 'x', $encoding);
  4118. // Trimming leading/trailing whitespace.
  4119. $filename = trim($filename);
  4120. // Trimming any leading/trailing dots.
  4121. $filename = trim($filename, '.');
  4122. $filename = trim($filename);
  4123. // Replacing remaining dangerous non-letter characters.
  4124. $filename = str_replace($search, $replace, $filename);
  4125. if ($strict == 'strict') {
  4126. //$filename = str_replace('-', '_', $filename); // See task #1848.
  4127. //$filename = preg_replace('/[^0-9A-Za-z_.\-]/', '', $filename);
  4128. //Removing "_" character see BT#3628
  4129. $filename = preg_replace('/[^0-9A-Za-z.\-_]/', '', $filename);
  4130. }
  4131. // Length is to be limited, so the file name to be acceptable by some operating systems.
  4132. $extension = (string)strrchr($filename, '.');
  4133. $extension_len = strlen($extension);
  4134. if ($extension_len > 0 && $extension_len < 250) {
  4135. $filename = substr($filename, 0, -$extension_len);
  4136. return substr($filename, 0, 250 - $extension_len).$extension;
  4137. }
  4138. return substr($filename, 0, 250);
  4139. }
  4140. /**
  4141. * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
  4142. * @author Ivan Tcholakov, 28-JUN-2006.
  4143. */
  4144. function api_request_uri() {
  4145. if (!empty($_SERVER['REQUEST_URI'])) {
  4146. return $_SERVER['REQUEST_URI'];
  4147. }
  4148. $uri = $_SERVER['SCRIPT_NAME'];
  4149. if (!empty($_SERVER['QUERY_STRING'])) {
  4150. $uri .= '?'.$_SERVER['QUERY_STRING'];
  4151. }
  4152. $_SERVER['REQUEST_URI'] = $uri;
  4153. return $uri;
  4154. }
  4155. /**
  4156. * Creates the "include_path" php-setting, following the rule that
  4157. * PEAR packages of Chamilo should be read before other external packages.
  4158. * To be used in global.inc.php only.
  4159. * @author Ivan Tcholakov, 06-NOV-2008.
  4160. */
  4161. function api_create_include_path_setting() {
  4162. $include_path = ini_get('include_path');
  4163. if (!empty($include_path)) {
  4164. $include_path_array = explode(PATH_SEPARATOR, $include_path);
  4165. $dot_found = array_search('.', $include_path_array);
  4166. if ($dot_found !== false) {
  4167. $result = array();
  4168. foreach ($include_path_array as $path) {
  4169. $result[] = $path;
  4170. if ($path == '.') {
  4171. // The path of Chamilo PEAR packages is to be inserted after the current directory path.
  4172. $result[] = api_get_path(LIBRARY_PATH).'pear';
  4173. }
  4174. }
  4175. return implode(PATH_SEPARATOR, $result);
  4176. }
  4177. // Current directory is not listed in the include_path setting, low probability is here.
  4178. return api_get_path(LIBRARY_PATH).'pear'.PATH_SEPARATOR.$include_path;
  4179. }
  4180. // The include_path setting is empty, low probability is here.
  4181. return api_get_path(LIBRARY_PATH).'pear';
  4182. }
  4183. /** Gets the current access_url id of the Chamilo Platform
  4184. * @author Julio Montoya <gugli100@gmail.com>
  4185. * @return int access_url_id of the current Chamilo Installation
  4186. */
  4187. function api_get_current_access_url_id() {
  4188. $access_url_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4189. $path = Database::escape_string(api_get_path(WEB_PATH));
  4190. $sql = "SELECT id FROM $access_url_table WHERE url = '".$path."'";
  4191. $result = Database::query($sql);
  4192. if (Database::num_rows($result) > 0) {
  4193. $access_url_id = Database::result($result, 0, 0);
  4194. return $access_url_id;
  4195. }
  4196. //if the url in WEB_PATH was not found, it can only mean that there is
  4197. // either a configuration problem or the first URL has not been defined yet
  4198. // (by default it is http://localhost/). Thus the more sensible thing we can
  4199. // do is return 1 (the main URL) as the user cannot hack this value anyway
  4200. return 1;
  4201. }
  4202. /**
  4203. * Gets the registered urls from a given user id
  4204. * @author Julio Montoya <gugli100@gmail.com>
  4205. * @return int user id
  4206. */
  4207. function api_get_access_url_from_user($user_id) {
  4208. $user_id = intval($user_id);
  4209. $table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4210. $table_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4211. $sql = "SELECT access_url_id FROM $table_url_rel_user url_rel_user INNER JOIN $table_url u
  4212. ON (url_rel_user.access_url_id = u.id)
  4213. WHERE user_id = ".Database::escape_string($user_id);
  4214. $result = Database::query($sql);
  4215. $url_list = array();
  4216. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4217. $url_list[] = $row['access_url_id'];
  4218. }
  4219. return $url_list;
  4220. }
  4221. /**
  4222. * Gets the status of a user in a course
  4223. * @param int user_id
  4224. * @param string course_code
  4225. * @return int user status
  4226. */
  4227. function api_get_status_of_user_in_course ($user_id, $course_code) {
  4228. $tbl_rel_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  4229. if (!empty($user_id) && !empty($course_code)) {
  4230. $user_id = Database::escape_string(intval($user_id));
  4231. $course_code = Database::escape_string($course_code);
  4232. $sql = 'SELECT status FROM '.$tbl_rel_course_user.'
  4233. WHERE user_id='.$user_id.' AND course_code="'.$course_code.'";';
  4234. $result = Database::query($sql);
  4235. $row_status = Database::fetch_array($result, 'ASSOC');
  4236. return $row_status['status'];
  4237. } else {
  4238. return 0;
  4239. }
  4240. }
  4241. /**
  4242. * Checks whether the curent user is in a course or not.
  4243. *
  4244. * @param string The course code - optional (takes it from session if not given)
  4245. * @return boolean
  4246. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  4247. */
  4248. function api_is_in_course($course_code = null) {
  4249. if (isset($_SESSION['_course']['sysCode'])) {
  4250. if (!empty($course_code)) {
  4251. return $course_code == $_SESSION['_course']['sysCode'];
  4252. }
  4253. return true;
  4254. }
  4255. return false;
  4256. }
  4257. /**
  4258. * Checks whether the curent user is in a group or not.
  4259. *
  4260. * @param string The group id - optional (takes it from session if not given)
  4261. * @param string The course code - optional (no additional check by course if course code is not given)
  4262. * @return boolean
  4263. * @author Ivan Tcholakov
  4264. */
  4265. function api_is_in_group($group_id = null, $course_code = null) {
  4266. if (!empty($course_code)) {
  4267. if (isset($_SESSION['_course']['sysCode'])) {
  4268. if ($course_code != $_SESSION['_course']['sysCode']) return false;
  4269. } else {
  4270. return false;
  4271. }
  4272. }
  4273. if (isset($_SESSION['_gid']) && $_SESSION['_gid'] != '') {
  4274. if (!empty($group_id)) {
  4275. return $group_id == $_SESSION['_gid'];
  4276. } else {
  4277. return true;
  4278. }
  4279. }
  4280. return false;
  4281. }
  4282. /**
  4283. * This function gets the hash in md5 or sha1 (it depends in the platform config) of a given password
  4284. * @param string password
  4285. * @return string password with the applied hash
  4286. */
  4287. function api_get_encrypted_password($password, $salt = '') {
  4288. global $_configuration;
  4289. $password_encryption = isset($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1';
  4290. switch ($password_encryption) {
  4291. case 'sha1':
  4292. return empty($salt) ? sha1($password) : sha1($password.$salt);
  4293. case 'none':
  4294. return $password;
  4295. case 'md5':
  4296. default:
  4297. return empty($salt) ? md5($password) : md5($password.$salt);
  4298. }
  4299. }
  4300. /**
  4301. * Checks whether a secret key is valid
  4302. * @param string $original_key_secret - secret key from (webservice) client
  4303. * @param string $security_key - security key from Chamilo
  4304. * @return boolean - true if secret key is valid, false otherwise
  4305. */
  4306. function api_is_valid_secret_key($original_key_secret, $security_key) {
  4307. global $_configuration;
  4308. return $original_key_secret == sha1($security_key);
  4309. }
  4310. /**
  4311. * Checks whether a user is into course
  4312. * @param string $course_id - the course id
  4313. * @param string $user_id - the user id
  4314. */
  4315. function api_is_user_of_course($course_id, $user_id) {
  4316. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4317. $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.' WHERE course_code="'.Database::escape_string($course_id).'" AND user_id="'.Database::escape_string($user_id).'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' ';
  4318. $result = Database::query($sql);
  4319. return Database::num_rows($result) == 1;
  4320. }
  4321. /**
  4322. * Checks whether the server's operating system is Windows (TM).
  4323. * @return boolean - true if the operating system is Windows, false otherwise
  4324. */
  4325. function api_is_windows_os() {
  4326. if (function_exists('php_uname')) {
  4327. // php_uname() exists as of PHP 4.0.2, according to the documentation.
  4328. // We expect that this function will always work for Chamilo 1.8.x.
  4329. $os = php_uname();
  4330. }
  4331. // The following methods are not needed, but let them stay, just in case.
  4332. elseif (isset($_ENV['OS'])) {
  4333. // Sometimes $_ENV['OS'] may not be present (bugs?)
  4334. $os = $_ENV['OS'];
  4335. }
  4336. elseif (defined('PHP_OS')) {
  4337. // PHP_OS means on which OS PHP was compiled, this is why
  4338. // using PHP_OS is the last choice for detection.
  4339. $os = PHP_OS;
  4340. } else {
  4341. return false;
  4342. }
  4343. return strtolower(substr((string)$os, 0, 3 )) == 'win';
  4344. }
  4345. /**
  4346. * This function informs whether the sent request is XMLHttpRequest
  4347. */
  4348. function api_is_xml_http_request() {
  4349. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  4350. }
  4351. /**
  4352. * Substitute for json_encode function for PHP version < 5.2.
  4353. *
  4354. * The following function has been adopted from Drupal's "Image Browser" project,
  4355. * @link http://drupal.org/project/imagebrowser
  4356. * version 6.x-2.x-dev, 2010-Mar-11,
  4357. * @link http://ftp.drupal.org/files/projects/imagebrowser-6.x-2.x-dev.tar.gz
  4358. */
  4359. if (!function_exists('json_encode')) {
  4360. function json_encode($a = false) {
  4361. if (is_null($a)) return 'null';
  4362. if ($a === false) return 'false';
  4363. if ($a === true) return 'true';
  4364. if (is_scalar($a)) {
  4365. if (is_float($a)) {
  4366. // Always use "." for floats.
  4367. return floatval(str_replace(",", ".", strval($a)));
  4368. }
  4369. if (is_string($a)) {
  4370. static $json_replaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
  4371. return '"' . str_replace($json_replaces[0], $json_replaces[1], $a) . '"';
  4372. }
  4373. else
  4374. return $a;
  4375. }
  4376. $is_list = true;
  4377. for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
  4378. if (key($a) !== $i) {
  4379. $is_list = false;
  4380. break;
  4381. }
  4382. }
  4383. $result = array();
  4384. if ($is_list) {
  4385. foreach ($a as $v) $result[] = json_encode($v);
  4386. return '[' . join(',', $result) . ']';
  4387. }
  4388. else {
  4389. foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
  4390. return '{' . join(',', $result) . '}';
  4391. }
  4392. }
  4393. }
  4394. /**
  4395. * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
  4396. * @link http://php.net/manual/en/function.getimagesize.php
  4397. * @link http://www.dokeos.com/forum/viewtopic.php?t=12345
  4398. * @link http://www.dokeos.com/forum/viewtopic.php?t=16355
  4399. */
  4400. function api_getimagesize($path) {
  4401. $image = new Image($path);
  4402. return $image->get_image_size();
  4403. }
  4404. /**
  4405. * This function resizes an image, with preserving its proportions (or aspect ratio).
  4406. * @author Ivan Tcholakov, MAY-2009.
  4407. * @param int $image System path or URL of the image
  4408. * @param int $target_width Targeted width
  4409. * @param int $target_height Targeted height
  4410. * @return array Calculated new width and height
  4411. */
  4412. function api_resize_image($image, $target_width, $target_height) {
  4413. $image_properties = api_getimagesize($image);
  4414. return api_calculate_image_size($image_properties['width'], $image_properties['height'], $target_width, $target_height);
  4415. }
  4416. /**
  4417. * This function calculates new image size, with preserving image's proportions (or aspect ratio).
  4418. * @author Ivan Tcholakov, MAY-2009.
  4419. * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
  4420. * @param int $image_width Initial width
  4421. * @param int $image_height Initial height
  4422. * @param int $target_width Targeted width
  4423. * @param int $target_height Targeted height
  4424. * @return array Calculated new width and height
  4425. */
  4426. function api_calculate_image_size($image_width, $image_height, $target_width, $target_height) {
  4427. // Only maths is here.
  4428. $result = array('width' => $image_width, 'height' => $image_height);
  4429. if ($image_width <= 0 || $image_height <= 0) {
  4430. return $result;
  4431. }
  4432. $resize_factor_width = $target_width / $image_width;
  4433. $resize_factor_height = $target_height / $image_height;
  4434. $delta_width = $target_width - $image_width * $resize_factor_height;
  4435. $delta_height = $target_height - $image_height * $resize_factor_width;
  4436. if ($delta_width > $delta_height) {
  4437. $result['width'] = ceil($image_width * $resize_factor_height);
  4438. $result['height'] = ceil($image_height * $resize_factor_height);
  4439. }
  4440. elseif ($delta_width < $delta_height) {
  4441. $result['width'] = ceil($image_width * $resize_factor_width);
  4442. $result['height'] = ceil($image_height * $resize_factor_width);
  4443. }
  4444. else {
  4445. $result['width'] = ceil($target_width);
  4446. $result['height'] = ceil($target_height);
  4447. }
  4448. return $result;
  4449. }
  4450. /**
  4451. * Returns a list of Chamilo's tools or
  4452. * checks whether a given identificator is a valid Chamilo's tool.
  4453. * @author Isaac flores paz
  4454. * @param string The tool name to filter
  4455. * @return mixed Filtered string or array
  4456. */
  4457. function api_get_tools_lists($my_tool = null) {
  4458. $tools_list = array(
  4459. TOOL_DOCUMENT, TOOL_THUMBNAIL, TOOL_HOTPOTATOES,
  4460. TOOL_CALENDAR_EVENT, TOOL_LINK, TOOL_COURSE_DESCRIPTION, TOOL_SEARCH,
  4461. TOOL_LEARNPATH, TOOL_ANNOUNCEMENT, TOOL_FORUM, TOOL_THREAD, TOOL_POST,
  4462. TOOL_DROPBOX, TOOL_QUIZ, TOOL_USER, TOOL_GROUP, TOOL_BLOGS, TOOL_CHAT,
  4463. TOOL_CONFERENCE, TOOL_STUDENTPUBLICATION, TOOL_TRACKING, TOOL_HOMEPAGE_LINK,
  4464. TOOL_COURSE_SETTING, TOOL_BACKUP, TOOL_COPY_COURSE_CONTENT, TOOL_RECYCLE_COURSE,
  4465. TOOL_COURSE_HOMEPAGE, TOOL_COURSE_RIGHTS_OVERVIEW, TOOL_UPLOAD, TOOL_COURSE_MAINTENANCE,
  4466. TOOL_VISIO, TOOL_VISIO_CONFERENCE, TOOL_VISIO_CLASSROOM, TOOL_SURVEY, TOOL_WIKI,
  4467. TOOL_GLOSSARY, TOOL_GRADEBOOK, TOOL_NOTEBOOK, TOOL_ATTENDANCE, TOOL_COURSE_PROGRESS
  4468. );
  4469. if (empty($my_tool)) {
  4470. return $tools_list;
  4471. }
  4472. return in_array($my_tool, $tools_list) ? $my_tool : '';
  4473. }
  4474. /**
  4475. * Checks whether we already approved the last version term and condition
  4476. * @param int user id
  4477. * @return bool true if we pass false otherwise
  4478. */
  4479. function api_check_term_condition($user_id) {
  4480. if (api_get_setting('allow_terms_conditions') == 'true') {
  4481. require_once api_get_path(LIBRARY_PATH).'legal.lib.php';
  4482. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  4483. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  4484. //check if exists terms and conditions
  4485. if (LegalManager::count() == 0) {
  4486. return true;
  4487. }
  4488. // Check the last user version_id passed
  4489. $sqlv = "SELECT field_value FROM $t_ufv ufv inner join $t_uf uf on ufv.field_id= uf.id
  4490. WHERE field_variable = 'legal_accept' AND user_id = ".intval($user_id);
  4491. $resv = Database::query($sqlv);
  4492. if (Database::num_rows($resv) > 0) {
  4493. $rowv = Database::fetch_row($resv);
  4494. $rowv = $rowv[0];
  4495. $user_conditions = explode(':', $rowv);
  4496. $version = $user_conditions[0];
  4497. $lang_id = $user_conditions[1];
  4498. $real_version = LegalManager::get_last_version($lang_id);
  4499. return $version >= $real_version;
  4500. }
  4501. return false;
  4502. }
  4503. return false;
  4504. }
  4505. /**
  4506. * Gets all information of a tool into course
  4507. * @param int The tool id
  4508. * @return array
  4509. */
  4510. function api_get_tool_information($tool_id) {
  4511. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4512. $course_id = api_get_course_int_id();
  4513. $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND id = ".intval($tool_id);
  4514. $rs = Database::query($sql);
  4515. return Database::fetch_array($rs);
  4516. }
  4517. /**
  4518. * Gets all information of a tool into course
  4519. * @param int The tool id
  4520. * @return array
  4521. */
  4522. function api_get_tool_information_by_name($name) {
  4523. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4524. $course_id = api_get_course_int_id();
  4525. $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  4526. $rs = Database::query($sql);
  4527. return Database::fetch_array($rs, 'ASSOC');
  4528. }
  4529. /* DEPRECATED FUNCTIONS */
  4530. /**
  4531. * Deprecated, use api_trunc_str() instead.
  4532. */
  4533. function shorten($input, $length = 15, $encoding = null) {
  4534. $length = intval($length);
  4535. if (!$length) {
  4536. $length = 15;
  4537. }
  4538. return api_trunc_str($input, $length, '...', false, $encoding);
  4539. }
  4540. /**
  4541. * DEPRECATED, use api_get_setting instead
  4542. */
  4543. function get_setting($variable, $key = NULL) {
  4544. global $_setting;
  4545. return api_get_setting($variable, $key);
  4546. }
  4547. /**
  4548. * deprecated: use api_is_allowed_to_edit() instead
  4549. */
  4550. function is_allowed_to_edit() {
  4551. return api_is_allowed_to_edit();
  4552. }
  4553. /**
  4554. * deprecated: 19-SEP-2009: Use api_get_path(TO_SYS, $url) instead.
  4555. */
  4556. function api_url_to_local_path($url) {
  4557. return api_get_path(TO_SYS, $url);
  4558. }
  4559. /**
  4560. * @deprecated 27-SEP-2009: Use Database::store_result($result) instead.
  4561. */
  4562. function api_store_result($result) {
  4563. return Database::store_result($result);
  4564. }
  4565. /**
  4566. * @deprecated 28-SEP-2009: Use Database::query($query, $file, $line) instead.
  4567. */
  4568. function api_sql_query($query, $file = '', $line = 0) {
  4569. return Database::query($query, $file, $line);
  4570. }
  4571. /**
  4572. * @deprecated 25-JAN-2010: See api_mail() and api_mail_html(), mail.lib.inc.php
  4573. *
  4574. * Send an email.
  4575. *
  4576. * Wrapper function for the standard php mail() function. Change this function
  4577. * to your needs. The parameters must follow the same rules as the standard php
  4578. * mail() function. Please look at the documentation on http://php.net/manual/en/function.mail.php
  4579. * @param string $to
  4580. * @param string $subject
  4581. * @param string $message
  4582. * @param string $additional_headers
  4583. * @param string $additional_parameters
  4584. * @author Ivan Tcholakov, 04-OCT-2009, a reworked version of this function.
  4585. * @link http://www.dokeos.com/forum/viewtopic.php?t=15557
  4586. */
  4587. function api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) {
  4588. require_once api_get_path(LIBRARY_PATH).'phpmailer/class.phpmailer.php';
  4589. if (empty($platform_email['SMTP_FROM_NAME'])) {
  4590. $platform_email['SMTP_FROM_NAME'] = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  4591. }
  4592. if (empty($platform_email['SMTP_FROM_EMAIL'])) {
  4593. $platform_email['SMTP_FROM_EMAIL'] = api_get_setting('emailAdministrator');
  4594. }
  4595. $matches = array();
  4596. if (preg_match('/([^<]*)<(.+)>/si', $to, $matches)) {
  4597. $recipient_name = trim($matches[1]);
  4598. $recipient_email = trim($matches[2]);
  4599. } else {
  4600. $recipient_name = '';
  4601. $recipient_email = trim($to);
  4602. }
  4603. $sender_name = '';
  4604. $sender_email = '';
  4605. $extra_headers = $additional_headers;
  4606. // Regular expression to test for valid email address.
  4607. // This should actually be revised to use the complete RFC3696 description.
  4608. // http://tools.ietf.org/html/rfc3696#section-3
  4609. //$regexp = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$"; // Deprecated, 13-OCT-2010.
  4610. $mail = new PHPMailer();
  4611. $mail->CharSet = $platform_email['SMTP_CHARSET'];
  4612. $mail->Mailer = $platform_email['SMTP_MAILER'];
  4613. $mail->Host = $platform_email['SMTP_HOST'];
  4614. $mail->Port = $platform_email['SMTP_PORT'];
  4615. if ($platform_email['SMTP_AUTH']) {
  4616. $mail->SMTPAuth = 1;
  4617. $mail->Username = $platform_email['SMTP_USER'];
  4618. $mail->Password = $platform_email['SMTP_PASS'];
  4619. }
  4620. $mail->Priority = 3; // 5 = low, 1 = high
  4621. $mail->AddCustomHeader('Errors-To: '.$platform_email['SMTP_FROM_EMAIL']);
  4622. $mail->IsHTML(0);
  4623. $mail->SMTPKeepAlive = true;
  4624. // Attachments.
  4625. // $mail->AddAttachment($path);
  4626. // $mail->AddAttachment($path, $filename);
  4627. if ($sender_email != '') {
  4628. $mail->From = $sender_email;
  4629. $mail->Sender = $sender_email;
  4630. //$mail->ConfirmReadingTo = $sender_email; // Disposition-Notification
  4631. } else {
  4632. $mail->From = $platform_email['SMTP_FROM_EMAIL'];
  4633. $mail->Sender = $platform_email['SMTP_FROM_EMAIL'];
  4634. //$mail->ConfirmReadingTo = $platform_email['SMTP_FROM_EMAIL']; // Disposition-Notification
  4635. }
  4636. if ($sender_name != '') {
  4637. $mail->FromName = $sender_name;
  4638. } else {
  4639. $mail->FromName = $platform_email['SMTP_FROM_NAME'];
  4640. }
  4641. $mail->Subject = $subject;
  4642. $mail->Body = $message;
  4643. // Only valid address are to be accepted.
  4644. //if (eregi( $regexp, $recipient_email )) { // Deprecated, 13-OCT-2010.
  4645. if (api_valid_email($recipient_email)) {
  4646. $mail->AddAddress($recipient_email, $recipient_name);
  4647. }
  4648. if ($extra_headers != '') {
  4649. $mail->AddCustomHeader($extra_headers);
  4650. }
  4651. // Send mail.
  4652. if (!$mail->Send()) {
  4653. return 0;
  4654. }
  4655. // Clear all the addresses.
  4656. $mail->ClearAddresses();
  4657. return 1;
  4658. }
  4659. /* END OF DEPRECATED FUNCTIONS SECTION */
  4660. /**
  4661. * Function used to protect a "global" admin script.
  4662. * The function blocks access when the user has no global platform admin rights.
  4663. * Global admins are the admins that are registered in the main.admin table AND the users who have access to the "principal" portal.
  4664. * That means that there is a record in the main.access_url_rel_user table with his user id and the access_url_id=1
  4665. *
  4666. * @author Julio Montoya
  4667. */
  4668. function api_is_global_platform_admin($user_id = null) {
  4669. $user_id = intval($user_id);
  4670. if (empty($user_id)) {
  4671. $user_id = api_get_user_id();
  4672. }
  4673. if (api_is_platform_admin_by_id($user_id)) {
  4674. $my_url_list = api_get_access_url_from_user($user_id);
  4675. // The admin is registered in the first "main" site with access_url_id = 1
  4676. if (in_array(1, $my_url_list)) {
  4677. return true;
  4678. } else {
  4679. return false;
  4680. }
  4681. }
  4682. return false;
  4683. }
  4684. function api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id = null) {
  4685. if (empty($my_user_id)) {
  4686. $my_user_id = api_get_user_id();
  4687. }
  4688. $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
  4689. $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
  4690. if ($iam_a_global_admin) {
  4691. //global admin can edit everything
  4692. return true;
  4693. } else {
  4694. //If i'm a simple admin
  4695. if (api_is_platform_admin_by_id($my_user_id)) {
  4696. if ($user_is_global_admin) {
  4697. return false;
  4698. } else {
  4699. return true;
  4700. }
  4701. } else {
  4702. return false;
  4703. }
  4704. }
  4705. }
  4706. function api_protect_super_admin($admin_id_to_check, $my_user_id = null) {
  4707. if (api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id)) {
  4708. return true;
  4709. } else {
  4710. api_not_allowed();
  4711. }
  4712. }
  4713. /**
  4714. * Function used to protect a global admin script.
  4715. * The function blocks access when the user has no global platform admin rights.
  4716. * See also the api_is_global_platform_admin() function wich defines who's a "global" admin
  4717. *
  4718. * @author Julio Montoya
  4719. */
  4720. function api_protect_global_admin_script() {
  4721. if (!api_is_global_platform_admin()) {
  4722. api_not_allowed();
  4723. return false;
  4724. }
  4725. return true;
  4726. }
  4727. /**
  4728. * Get actived template
  4729. * @param string theme type (optional: default)
  4730. * @param string path absolute(abs) or relative(rel) (optional:rel)
  4731. * @return string actived template path
  4732. */
  4733. function api_get_template($path_type = 'rel') {
  4734. $path_types = array('rel', 'abs');
  4735. $template_path = '';
  4736. if (in_array($path_type, $path_types)) {
  4737. if ($path_type == 'rel') {
  4738. $template_path = api_get_path(SYS_TEMPLATE_PATH);
  4739. } else {
  4740. $template_path = api_get_path(WEB_TEMPLATE_PATH);
  4741. }
  4742. }
  4743. $actived_theme = 'default';
  4744. if (api_get_setting('active_template')) {
  4745. $actived_theme = api_get_setting('active_template');
  4746. }
  4747. $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
  4748. return $actived_theme_path;
  4749. }
  4750. /**
  4751. * Check browser support for type files
  4752. ** This function check if the users browser support a file format or return the current browser and major ver when $format=check_browser
  4753. * @param string $format
  4754. *
  4755. * @return bool, or return text array if $format=check_browser
  4756. *
  4757. * @author Juan Carlos Raña Trabado
  4758. */
  4759. function api_browser_support($format="") {
  4760. require_once api_get_path(LIBRARY_PATH).'browser/Browser.php';
  4761. $browser = new Browser();
  4762. //print_r($browser);
  4763. $current_browser = $browser->getBrowser();
  4764. $a_versiontemp = explode('.', $browser->getVersion());
  4765. $current_majorver= $a_versiontemp[0];
  4766. //native svg support
  4767. if ($format=='svg'){
  4768. if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) || ($current_browser == 'Firefox' && $current_majorver > 1) || ($current_browser == 'Safari' && $current_majorver >= 4) || ($current_browser == 'Chrome' && $current_majorver >= 1) || ($current_browser == 'Opera' && $current_majorver >= 9)) {
  4769. return true;
  4770. }
  4771. else {
  4772. return false;
  4773. }
  4774. }
  4775. elseif($format=='pdf'){
  4776. //native pdf support
  4777. if($current_browser == 'Chrome' && $current_majorver >= 6){
  4778. return true;
  4779. }
  4780. else{
  4781. return false;
  4782. }
  4783. }
  4784. elseif($format=='tif' || $format=='tiff'){
  4785. //native tif support
  4786. if($current_browser == 'Safari' && $current_majorver >= 5){
  4787. return true;
  4788. }
  4789. else{
  4790. return false;
  4791. }
  4792. }
  4793. elseif($format=='ogg' || $format=='ogx'|| $format=='ogv' || $format=='oga'){
  4794. //native ogg, ogv,oga support
  4795. if (($current_browser == 'Firefox' && $current_majorver >= 3) || ($current_browser == 'Chrome' && $current_majorver >= 3) || ($current_browser == 'Opera' && $current_majorver >= 9)) {
  4796. return true;
  4797. }
  4798. else {
  4799. return false;
  4800. }
  4801. }
  4802. elseif($format=='mpg' || $format=='mpeg'){
  4803. //native mpg support
  4804. if(($current_browser == 'Safari' && $current_majorver >= 5)){
  4805. return true;
  4806. }
  4807. else{
  4808. return false;
  4809. }
  4810. }
  4811. elseif($format=='mp4'){
  4812. //native mp4 support (TODO: Android, iPhone)
  4813. if($current_browser == 'Android' || $current_browser == 'iPhone') {
  4814. return true;
  4815. }
  4816. else{
  4817. return false;
  4818. }
  4819. }
  4820. elseif($format=='mov'){
  4821. //native mov support( TODO:check iPhone)
  4822. if($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone'){
  4823. return true;
  4824. }
  4825. else{
  4826. return false;
  4827. }
  4828. }
  4829. elseif($format=='avi'){
  4830. //native avi support
  4831. if($current_browser == 'Safari' && $current_majorver >= 5){
  4832. return true;
  4833. }
  4834. else{
  4835. return false;
  4836. }
  4837. }
  4838. elseif($format=='wmv'){
  4839. //native wmv support
  4840. if($current_browser == 'Firefox' && $current_majorver >= 4){
  4841. return true;
  4842. }
  4843. else{
  4844. return false;
  4845. }
  4846. }
  4847. elseif($format=='webm'){
  4848. //native webm support (TODO:check IE9, Chrome9, Android)
  4849. if(($current_browser == 'Firefox' && $current_majorver >= 4) || ($current_browser == 'Opera' && $current_majorver >= 9) || ($current_browser == 'Internet Explorer' && $current_majorver >= 9)|| ($current_browser == 'Chrome' && $current_majorver >=9)|| $current_browser == 'Android'){
  4850. return true;
  4851. }
  4852. else{
  4853. return false;
  4854. }
  4855. }
  4856. elseif($format=='wav'){
  4857. //native wav support (only some codecs !)
  4858. if(($current_browser == 'Firefox' && $current_majorver >= 4) || ($current_browser == 'Safari' && $current_majorver >= 5) || ($current_browser == 'Opera' && $current_majorver >= 9) || ($current_browser == 'Internet Explorer' && $current_majorver >= 9)|| ($current_browser == 'Chrome' && $current_majorver > 9)|| $current_browser == 'Android' || $current_browser == 'iPhone'){
  4859. return true;
  4860. }
  4861. else{
  4862. return false;
  4863. }
  4864. }
  4865. elseif($format=='mid' || $format=='kar'){
  4866. //native midi support (TODO:check Android)
  4867. if($current_browser == 'Opera'&& $current_majorver >= 9 || $current_browser == 'Android'){
  4868. return true;
  4869. }
  4870. else{
  4871. return false;
  4872. }
  4873. }
  4874. elseif($format=='wma'){
  4875. //native wma support
  4876. if($current_browser == 'Firefox' && $current_majorver >= 4){
  4877. return true;
  4878. }
  4879. else{
  4880. return false;
  4881. }
  4882. }
  4883. elseif($format=='au'){
  4884. //native au support
  4885. if($current_browser == 'Safari' && $current_majorver >= 5){
  4886. return true;
  4887. }
  4888. else{
  4889. return false;
  4890. }
  4891. }
  4892. elseif($format=='mp3'){
  4893. //native mp3 support (TODO:check Android, iPhone)
  4894. if(($current_browser == 'Safari' && $current_majorver >= 5) || ($current_browser == 'Chrome' && $current_majorver >=6)|| ($current_browser == 'Internet Explorer' && $current_majorver >= 9)|| $current_browser == 'Android' || $current_browser == 'iPhone'){
  4895. return true;
  4896. }
  4897. else{
  4898. return false;
  4899. }
  4900. }
  4901. elseif($format=="check_browser"){
  4902. $array_check_browser=array($current_browser, $current_majorver);
  4903. return $array_check_browser;
  4904. }
  4905. else{
  4906. return false;
  4907. }
  4908. }
  4909. /**
  4910. * This function checks if exist path and file browscap.ini
  4911. * In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system
  4912. * http://php.net/manual/en/function.get-browser.php
  4913. *
  4914. * @return bool
  4915. *
  4916. * @author Juan Carlos Raña Trabado
  4917. */
  4918. function api_check_browscap() {
  4919. $setting = ini_get('browscap');
  4920. if ($setting) {
  4921. $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
  4922. if (strpos($setting, 'browscap.ini') && !empty($browser)) {
  4923. return true;
  4924. }
  4925. }
  4926. return false;
  4927. }
  4928. /**
  4929. * Returns the <script> HTML tag
  4930. */
  4931. function api_get_js($file) {
  4932. return '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
  4933. }
  4934. /**
  4935. * Returns the <link> HTML tag
  4936. */
  4937. function api_get_css($file) {
  4938. return '<link rel="stylesheet" href="'.$file.'" type="text/css" />'."\n";
  4939. }
  4940. /**
  4941. * Returns the js header to include the jquery library
  4942. */
  4943. function api_get_jquery_js() {
  4944. return api_get_js('jquery.min.js');
  4945. }
  4946. /**
  4947. * Returns the jquery-ui library js headers
  4948. * @param bool add the jqgrid library
  4949. * @return string html tags
  4950. *
  4951. */
  4952. function api_get_jquery_ui_js($include_jqgrid = false) {
  4953. $libraries = array('jquery-ui');
  4954. if ($include_jqgrid) {
  4955. $libraries[]='jqgrid';
  4956. }
  4957. return api_get_jquery_libraries_js($libraries);
  4958. }
  4959. function api_get_jqgrid_js() {
  4960. return api_get_jquery_libraries_js(array('jqgrid'));
  4961. }
  4962. /**
  4963. * Returns the jquery library js and css headers
  4964. *
  4965. * @param array list of jquery libraries supported jquery-ui, jqgrid
  4966. * @param bool add the jquery library
  4967. * @return string html tags
  4968. *
  4969. */
  4970. function api_get_jquery_libraries_js($libraries) {
  4971. $js = '';
  4972. $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
  4973. //jquery-ui js and css
  4974. if (in_array('jquery-ui', $libraries)) {
  4975. //Jquery ui
  4976. $theme = 'smoothness'; // Current themes: cupertino, smoothness, ui-lightness. Find the themes folder in main/inc/lib/javascript/jquery-ui
  4977. $jquery_ui_version = '1.8.17';
  4978. //$js .= '<link rel="stylesheet" href="'.$js_path.'jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.css" type="text/css">';
  4979. $js .= api_get_css($js_path.'jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.css');
  4980. $js .= api_get_js('jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.min.js');
  4981. }
  4982. if (in_array('jquery-ui-i18n', $libraries)) {
  4983. $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
  4984. }
  4985. //jqgrid js and css
  4986. if (in_array('jqgrid', $libraries)) {
  4987. $languaje = 'en';
  4988. $platform_isocode = strtolower(api_get_language_isocode());
  4989. //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  4990. $jqgrid_langs = array('bg', 'bg1251', 'cat','cn','cs','da','de','el','en','es','fa','fi','fr','gl','he','hu','is','it','ja','nl','no','pl','pt-br','pt','ro','ru','sk','sr','sv','tr','ua');
  4991. if (in_array($platform_isocode, $jqgrid_langs)) {
  4992. $languaje = $platform_isocode;
  4993. }
  4994. //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
  4995. $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
  4996. $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
  4997. $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
  4998. }
  4999. //Document multiple upload funcionality
  5000. if (in_array('jquery-upload', $libraries)) {
  5001. $js .= api_get_js('jquery-upload/jquery.fileupload.js');
  5002. $js .= api_get_js('jquery-upload/jquery.fileupload-ui.js');
  5003. $js .= api_get_css($js_path.'jquery-upload/jquery.fileupload-ui.css');
  5004. }
  5005. //jquery-ui css changes for Chamilo
  5006. if (in_array('jquery-ui',$libraries)) {
  5007. //Adding default CSS changes of the jquery-ui themes for Chamilo in order to preserve the original jquery-ui css
  5008. $js .= api_get_css($js_path.'jquery-ui/default.css');
  5009. }
  5010. if (in_array('bxslider',$libraries)) {
  5011. $js .= api_get_js('bxslider/jquery.bxSlider.min.js');
  5012. $js .= api_get_css($js_path.'bxslider/bx_styles/bx_styles.css');
  5013. }
  5014. return $js;
  5015. }
  5016. /**
  5017. * Returns the course's URL
  5018. *
  5019. * This function relies on api_get_course_info()
  5020. * @param string The course code - optional (takes it from session if not given)
  5021. * @param int The session id - optional (takes it from session if not given)
  5022. * @return mixed The URL of the course or null if something does not work
  5023. * @author Julio Montoya <gugli100@gmail.com>
  5024. */
  5025. function api_get_course_url($course_code = null, $session_id = null) {
  5026. $session_url = '';
  5027. if (empty($course_code)) {
  5028. $course_info = api_get_course_info();
  5029. } else {
  5030. $course_info = api_get_course_info($course_code);
  5031. }
  5032. if (empty($session_id)) {
  5033. if (api_get_session_id() != 0)
  5034. $session_url = '?id_session='.api_get_session_id();
  5035. } else {
  5036. $session_url = '?id_session='.intval($session_id);
  5037. }
  5038. if (!empty($course_info['path'])) {
  5039. return api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.$session_url;
  5040. }
  5041. return null;
  5042. }
  5043. /**
  5044. *
  5045. * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on
  5046. * @return bool true if multi site is enabled
  5047. *
  5048. * */
  5049. function api_get_multiple_access_url() {
  5050. global $_configuration;
  5051. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  5052. return true;
  5053. }
  5054. return false;
  5055. }
  5056. /**
  5057. * Returns a md5 unique id
  5058. * @todo add more parameters
  5059. */
  5060. function api_get_unique_id() {
  5061. $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
  5062. return $id;
  5063. }
  5064. function api_get_home_path() {
  5065. $home = 'home/';
  5066. if (api_get_multiple_access_url()) {
  5067. $access_url_id = api_get_current_access_url_id();
  5068. $url_info = api_get_access_url($access_url_id);
  5069. $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
  5070. $clean_url = replace_dangerous_char($url);
  5071. $clean_url = str_replace('/', '-', $clean_url);
  5072. $clean_url .= '/';
  5073. // if $clean_url == "localhost/" means that the multiple URL was not well configured we don't rename the $home variable
  5074. if ($clean_url != 'localhost/')
  5075. $home = 'home/'.$clean_url;
  5076. }
  5077. return $home;
  5078. }
  5079. function api_get_course_table_condition($and = true) {
  5080. $course_id = api_get_course_int_id();
  5081. $condition = '';
  5082. $condition_add = $and ? " AND " : " WHERE ";
  5083. if (!empty($course_id)) {
  5084. $condition = " $condition_add c_id = $course_id";
  5085. }
  5086. return $condition;
  5087. }
  5088. function api_grading_model_functions($grading_model, $action = 'to_array') {
  5089. $return = null;
  5090. if (empty($grading_model)) {
  5091. return null;
  5092. }
  5093. $elements = array('A','B','C','D','E','F','G','H','I','J','K','L','M');
  5094. if (in_array($action, array('to_array', 'decorate'))) {
  5095. $parts = explode('/', $grading_model);
  5096. $return['denominator'] = $parts[1];
  5097. $sums = explode('+', $parts[0]);
  5098. $j = 0;
  5099. foreach($sums as $item) {
  5100. $item = explode('*', $item);
  5101. $per = 0;
  5102. if (!empty($return['denominator'])) {
  5103. $per = $item[0]/$return['denominator']*100;
  5104. }
  5105. $return['items'][] =array( 'letter' => $elements[$j],
  5106. 'value' => $item[0],
  5107. 'percentage'=> $per.'%');
  5108. $j++;
  5109. }
  5110. if ($action == 'decorate') {
  5111. $return_value = '';
  5112. $items = $return['items'];
  5113. $j = 1;
  5114. foreach ($items as $item) {
  5115. $letter = $item['letter'];
  5116. $value = $item['value'];
  5117. $sum = '+';
  5118. if (count($items) == $j){
  5119. $sum = '';
  5120. }
  5121. $return_value = $return_value.' '.$value.'*'.$letter." $sum ";
  5122. $j++;
  5123. }
  5124. $return = ' ('.$return_value.') / '.$return['denominator'];
  5125. }
  5126. }
  5127. return $return;
  5128. }