main_api.lib.php 210 KB

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