extra_field.lib.php 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
  5. use Chamilo\CoreBundle\Entity\Tag;
  6. /**
  7. * Class ExtraField.
  8. */
  9. class ExtraField extends Model
  10. {
  11. const FIELD_TYPE_TEXT = 1;
  12. const FIELD_TYPE_TEXTAREA = 2;
  13. const FIELD_TYPE_RADIO = 3;
  14. const FIELD_TYPE_SELECT = 4;
  15. const FIELD_TYPE_SELECT_MULTIPLE = 5;
  16. const FIELD_TYPE_DATE = 6;
  17. const FIELD_TYPE_DATETIME = 7;
  18. const FIELD_TYPE_DOUBLE_SELECT = 8;
  19. const FIELD_TYPE_DIVIDER = 9;
  20. const FIELD_TYPE_TAG = 10;
  21. const FIELD_TYPE_TIMEZONE = 11;
  22. const FIELD_TYPE_SOCIAL_PROFILE = 12;
  23. const FIELD_TYPE_CHECKBOX = 13;
  24. const FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
  25. const FIELD_TYPE_INTEGER = 15;
  26. const FIELD_TYPE_FILE_IMAGE = 16;
  27. const FIELD_TYPE_FLOAT = 17;
  28. const FIELD_TYPE_FILE = 18;
  29. const FIELD_TYPE_VIDEO_URL = 19;
  30. const FIELD_TYPE_LETTERS_ONLY = 20;
  31. const FIELD_TYPE_ALPHANUMERIC = 21;
  32. const FIELD_TYPE_LETTERS_SPACE = 22;
  33. const FIELD_TYPE_ALPHANUMERIC_SPACE = 23;
  34. const FIELD_TYPE_GEOLOCALIZATION = 24;
  35. const FIELD_TYPE_GEOLOCALIZATION_COORDINATES = 25;
  36. const FIELD_TYPE_SELECT_WITH_TEXT_FIELD = 26;
  37. const FIELD_TYPE_TRIPLE_SELECT = 27;
  38. public $columns = [
  39. 'id',
  40. 'field_type',
  41. 'variable',
  42. 'display_text',
  43. 'default_value',
  44. 'field_order',
  45. 'visible_to_self',
  46. 'visible_to_others',
  47. 'changeable',
  48. 'filter',
  49. 'extra_field_type',
  50. //Enable this when field_loggeable is introduced as a table field (2.0)
  51. //'field_loggeable',
  52. 'created_at',
  53. ];
  54. public $ops = [
  55. 'eq' => '=', //equal
  56. 'ne' => '<>', //not equal
  57. 'lt' => '<', //less than
  58. 'le' => '<=', //less than or equal
  59. 'gt' => '>', //greater than
  60. 'ge' => '>=', //greater than or equal
  61. 'bw' => 'LIKE', //begins with
  62. 'bn' => 'NOT LIKE', //doesn't begin with
  63. 'in' => 'LIKE', //is in
  64. 'ni' => 'NOT LIKE', //is not in
  65. 'ew' => 'LIKE', //ends with
  66. 'en' => 'NOT LIKE', //doesn't end with
  67. 'cn' => 'LIKE', //contains
  68. 'nc' => 'NOT LIKE', //doesn't contain
  69. ];
  70. public $type = 'user';
  71. public $pageName;
  72. public $pageUrl;
  73. public $extraFieldType = 0;
  74. public $table_field_options;
  75. public $table_field_values;
  76. public $table_field_tag;
  77. public $table_field_rel_tag;
  78. public $handler_id;
  79. public $primaryKey;
  80. /**
  81. * @param string $type
  82. */
  83. public function __construct($type)
  84. {
  85. parent::__construct();
  86. $this->type = $type;
  87. $this->table = Database::get_main_table(TABLE_EXTRA_FIELD);
  88. $this->table_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  89. $this->table_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  90. $this->table_field_tag = Database::get_main_table(TABLE_MAIN_TAG);
  91. $this->table_field_rel_tag = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
  92. $this->handler_id = 'item_id';
  93. switch ($this->type) {
  94. case 'calendar_event':
  95. $this->extraFieldType = EntityExtraField::CALENDAR_FIELD_TYPE;
  96. break;
  97. case 'course':
  98. $this->extraFieldType = EntityExtraField::COURSE_FIELD_TYPE;
  99. $this->primaryKey = 'id';
  100. break;
  101. case 'user':
  102. $this->extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  103. $this->primaryKey = 'id';
  104. break;
  105. case 'session':
  106. $this->extraFieldType = EntityExtraField::SESSION_FIELD_TYPE;
  107. $this->primaryKey = 'id';
  108. break;
  109. case 'exercise':
  110. $this->extraFieldType = EntityExtraField::EXERCISE_FIELD_TYPE;
  111. break;
  112. case 'question':
  113. $this->extraFieldType = EntityExtraField::QUESTION_FIELD_TYPE;
  114. break;
  115. case 'lp':
  116. $this->extraFieldType = EntityExtraField::LP_FIELD_TYPE;
  117. break;
  118. case 'lp_item':
  119. $this->extraFieldType = EntityExtraField::LP_ITEM_FIELD_TYPE;
  120. break;
  121. case 'skill':
  122. $this->extraFieldType = EntityExtraField::SKILL_FIELD_TYPE;
  123. break;
  124. case 'work':
  125. $this->extraFieldType = EntityExtraField::WORK_FIELD_TYPE;
  126. break;
  127. case 'career':
  128. $this->extraFieldType = EntityExtraField::CAREER_FIELD_TYPE;
  129. break;
  130. case 'user_certificate':
  131. $this->extraFieldType = EntityExtraField::USER_CERTIFICATE;
  132. break;
  133. case 'survey':
  134. $this->extraFieldType = EntityExtraField::SURVEY_FIELD_TYPE;
  135. break;
  136. case 'scheduled_announcement':
  137. $this->extraFieldType = EntityExtraField::SCHEDULED_ANNOUNCEMENT;
  138. break;
  139. case 'terms_and_condition':
  140. $this->extraFieldType = EntityExtraField::TERMS_AND_CONDITION_TYPE;
  141. break;
  142. case 'forum_category':
  143. $this->extraFieldType = EntityExtraField::FORUM_CATEGORY_TYPE;
  144. break;
  145. case 'forum_post':
  146. $this->extraFieldType = EntityExtraField::FORUM_POST_TYPE;
  147. break;
  148. }
  149. $this->pageUrl = 'extra_fields.php?type='.$this->type;
  150. // Example QuestionFields
  151. $this->pageName = get_lang(ucwords($this->type).'Fields');
  152. }
  153. /**
  154. * @return int
  155. */
  156. public function getExtraFieldType()
  157. {
  158. return (int) $this->extraFieldType;
  159. }
  160. /**
  161. * @return array
  162. */
  163. public static function getValidExtraFieldTypes()
  164. {
  165. $result = [
  166. 'user',
  167. 'course',
  168. 'session',
  169. 'question',
  170. 'lp',
  171. 'calendar_event',
  172. 'lp_item',
  173. 'skill',
  174. 'work',
  175. 'career',
  176. 'user_certificate',
  177. 'survey',
  178. 'terms_and_condition',
  179. 'forum_category',
  180. 'forum_post',
  181. 'exercise',
  182. ];
  183. if (api_get_configuration_value('allow_scheduled_announcements')) {
  184. $result[] = 'scheduled_announcement';
  185. }
  186. return $result;
  187. }
  188. /**
  189. * @return int
  190. */
  191. public function get_count()
  192. {
  193. $em = Database::getManager();
  194. $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
  195. $query->select('count(e.id)');
  196. $query->where('e.extraFieldType = :type');
  197. $query->setParameter('type', $this->getExtraFieldType());
  198. return $query->getQuery()->getSingleScalarResult();
  199. }
  200. /**
  201. * @param string $sidx
  202. * @param string $sord
  203. * @param int $start
  204. * @param int $limit
  205. *
  206. * @return array
  207. */
  208. public function getAllGrid($sidx, $sord, $start, $limit)
  209. {
  210. switch ($sidx) {
  211. case 'field_order':
  212. $sidx = 'e.fieldOrder';
  213. break;
  214. case 'variable':
  215. $sidx = 'e.variable';
  216. break;
  217. case 'display_text':
  218. $sidx = 'e.displayText';
  219. break;
  220. case 'changeable':
  221. $sidx = 'e.changeable';
  222. break;
  223. case 'visible_to_self':
  224. $sidx = 'e.visibleToSelf';
  225. break;
  226. case 'visible_to_others':
  227. $sidx = 'e.visibleToOthers';
  228. break;
  229. case 'filter':
  230. $sidx = 'e.filter';
  231. break;
  232. }
  233. $em = Database::getManager();
  234. $query = $em->getRepository('ChamiloCoreBundle:ExtraField')->createQueryBuilder('e');
  235. $query->select('e')
  236. ->where('e.extraFieldType = :type')
  237. ->setParameter('type', $this->getExtraFieldType())
  238. ->orderBy($sidx, $sord)
  239. ->setFirstResult($start)
  240. ->setMaxResults($limit);
  241. return $query->getQuery()->getArrayResult();
  242. }
  243. /**
  244. * Get an array of all the values from the extra_field and extra_field_options tables
  245. * based on the current object's type.
  246. *
  247. * @param array $conditions
  248. * @param null $order_field_options_by
  249. *
  250. * @return array
  251. */
  252. public function get_all($conditions = [], $order_field_options_by = null)
  253. {
  254. $conditions = Database::parse_conditions(['where' => $conditions]);
  255. if (empty($conditions)) {
  256. $conditions .= ' WHERE extra_field_type = '.$this->extraFieldType;
  257. } else {
  258. $conditions .= ' AND extra_field_type = '.$this->extraFieldType;
  259. }
  260. $sql = "SELECT * FROM $this->table
  261. $conditions
  262. ORDER BY field_order ASC
  263. ";
  264. $result = Database::query($sql);
  265. $extraFields = Database::store_result($result, 'ASSOC');
  266. $option = new ExtraFieldOption($this->type);
  267. if (!empty($extraFields)) {
  268. foreach ($extraFields as &$extraField) {
  269. $extraField['display_text'] = $this->translateDisplayName(
  270. $extraField['variable'],
  271. $extraField['display_text']
  272. );
  273. $extraField['options'] = $option->get_field_options_by_field(
  274. $extraField['id'],
  275. false,
  276. $order_field_options_by
  277. );
  278. }
  279. }
  280. return $extraFields;
  281. }
  282. /**
  283. * @param string $variable
  284. *
  285. * @return array|bool
  286. */
  287. public function get_handler_field_info_by_field_variable($variable)
  288. {
  289. $variable = Database::escape_string($variable);
  290. $sql = "SELECT * FROM {$this->table}
  291. WHERE
  292. variable = '$variable' AND
  293. extra_field_type = $this->extraFieldType";
  294. $result = Database::query($sql);
  295. if (Database::num_rows($result)) {
  296. $row = Database::fetch_array($result, 'ASSOC');
  297. if ($row) {
  298. $row['display_text'] = $this->translateDisplayName(
  299. $row['variable'],
  300. $row['display_text']
  301. );
  302. // All the options of the field
  303. $sql = "SELECT * FROM $this->table_field_options
  304. WHERE field_id='".intval($row['id'])."'
  305. ORDER BY option_order ASC";
  306. $result = Database::query($sql);
  307. while ($option = Database::fetch_array($result)) {
  308. $row['options'][$option['id']] = $option;
  309. }
  310. return $row;
  311. }
  312. }
  313. return false;
  314. }
  315. /**
  316. * Get all the field info for tags.
  317. *
  318. * @param string $variable
  319. *
  320. * @return array|bool
  321. */
  322. public function get_handler_field_info_by_tags($variable)
  323. {
  324. $variable = Database::escape_string($variable);
  325. $sql = "SELECT * FROM {$this->table}
  326. WHERE
  327. variable = '$variable' AND
  328. extra_field_type = $this->extraFieldType";
  329. $result = Database::query($sql);
  330. if (Database::num_rows($result)) {
  331. $row = Database::fetch_array($result, 'ASSOC');
  332. $row['display_text'] = $this->translateDisplayName(
  333. $row['variable'],
  334. $row['display_text']
  335. );
  336. // All the tags of the field
  337. $sql = "SELECT * FROM $this->table_field_tag
  338. WHERE field_id='".intval($row['id'])."'
  339. ORDER BY id ASC";
  340. $result = Database::query($sql);
  341. while ($option = Database::fetch_array($result, 'ASSOC')) {
  342. $row['options'][$option['id']] = $option;
  343. }
  344. return $row;
  345. } else {
  346. return false;
  347. }
  348. }
  349. /**
  350. * @param int $fieldId
  351. *
  352. * @return array|bool
  353. */
  354. public function getFieldInfoByFieldId($fieldId)
  355. {
  356. $fieldId = (int) $fieldId;
  357. $sql = "SELECT * FROM {$this->table}
  358. WHERE
  359. id = '$fieldId' AND
  360. extra_field_type = $this->extraFieldType";
  361. $result = Database::query($sql);
  362. if (Database::num_rows($result)) {
  363. $row = Database::fetch_array($result, 'ASSOC');
  364. // All the options of the field
  365. $sql = "SELECT * FROM $this->table_field_options
  366. WHERE field_id='".$fieldId."'
  367. ORDER BY option_order ASC";
  368. $result = Database::query($sql);
  369. while ($option = Database::fetch_array($result)) {
  370. $row['options'][$option['id']] = $option;
  371. }
  372. return $row;
  373. } else {
  374. return false;
  375. }
  376. }
  377. /**
  378. * @return int
  379. */
  380. public function get_max_field_order()
  381. {
  382. $sql = "SELECT MAX(field_order)
  383. FROM {$this->table}
  384. WHERE
  385. extra_field_type = '.$this->extraFieldType.'";
  386. $res = Database::query($sql);
  387. $order = 0;
  388. if (Database::num_rows($res) > 0) {
  389. $row = Database::fetch_row($res);
  390. $order = $row[0] + 1;
  391. }
  392. return $order;
  393. }
  394. /**
  395. * @param string $handler
  396. *
  397. * @return array
  398. */
  399. public static function get_extra_fields_by_handler($handler)
  400. {
  401. $types = [];
  402. $types[self::FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
  403. $types[self::FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
  404. $types[self::FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
  405. $types[self::FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
  406. $types[self::FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
  407. $types[self::FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
  408. $types[self::FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
  409. $types[self::FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
  410. $types[self::FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
  411. $types[self::FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
  412. $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
  413. $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
  414. $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
  415. $types[self::FIELD_TYPE_CHECKBOX] = get_lang('FieldTypeCheckbox');
  416. $types[self::FIELD_TYPE_INTEGER] = get_lang('FieldTypeInteger');
  417. $types[self::FIELD_TYPE_FILE_IMAGE] = get_lang('FieldTypeFileImage');
  418. $types[self::FIELD_TYPE_FLOAT] = get_lang('FieldTypeFloat');
  419. $types[self::FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
  420. $types[self::FIELD_TYPE_VIDEO_URL] = get_lang('FieldTypeVideoUrl');
  421. $types[self::FIELD_TYPE_LETTERS_ONLY] = get_lang('FieldTypeOnlyLetters');
  422. $types[self::FIELD_TYPE_ALPHANUMERIC] = get_lang('FieldTypeAlphanumeric');
  423. $types[self::FIELD_TYPE_LETTERS_SPACE] = get_lang('FieldTypeLettersSpaces');
  424. $types[self::FIELD_TYPE_ALPHANUMERIC_SPACE] = get_lang('FieldTypeAlphanumericSpaces');
  425. $types[self::FIELD_TYPE_GEOLOCALIZATION] = get_lang('Geolocalization');
  426. $types[self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES] = get_lang('GeolocalizationCoordinates');
  427. $types[self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD] = get_lang('FieldTypeSelectWithTextField');
  428. $types[self::FIELD_TYPE_TRIPLE_SELECT] = get_lang('FieldTypeTripleSelect');
  429. switch ($handler) {
  430. case 'course':
  431. case 'session':
  432. case 'user':
  433. case 'skill':
  434. break;
  435. }
  436. return $types;
  437. }
  438. /**
  439. * Add elements to a form.
  440. *
  441. * @param FormValidator $form The form object to which to attach this element
  442. * @param int $itemId The item (course, user, session, etc) this extra_field is linked to
  443. * @param array $exclude Variables of extra field to exclude
  444. * @param bool $filter Whether to get only the fields with the "filter" flag set to 1 (true) or not (false)
  445. * @param bool $useTagAsSelect Whether to show tag fields as select drop-down or not
  446. * @param array $showOnlyTheseFields Limit the extra fields shown to just the list given here
  447. * @param array $orderFields An array containing the names of the fields shown, in the right order
  448. * @param array $extraData
  449. * @param bool $orderDependingDefaults
  450. * @param bool $adminPermissions
  451. * @param array $separateExtraMultipleSelect
  452. * @param array $customLabelsExtraMultipleSelect
  453. * @param bool $addEmptyOptionSelects
  454. * @param array $introductionTextList
  455. * @param array $requiredFields
  456. * @param bool $hideGeoLocalizationDetails
  457. *
  458. * @throws Exception
  459. *
  460. * @return array|bool If relevant, returns a one-element array with JS code to be added to the page HTML headers.
  461. * Returns false if the form object was not given
  462. */
  463. public function addElements(
  464. $form,
  465. $itemId = 0,
  466. $exclude = [],
  467. $filter = false,
  468. $useTagAsSelect = false,
  469. $showOnlyTheseFields = [],
  470. $orderFields = [],
  471. $extraData = [],
  472. $orderDependingDefaults = false,
  473. $adminPermissions = false,
  474. $separateExtraMultipleSelect = [],
  475. $customLabelsExtraMultipleSelect = [],
  476. $addEmptyOptionSelects = false,
  477. $introductionTextList = [],
  478. $requiredFields = [],
  479. $hideGeoLocalizationDetails = false,
  480. $help = false
  481. ) {
  482. if (empty($form)) {
  483. return false;
  484. }
  485. $itemId = (int) $itemId;
  486. $form->addHidden('item_id', $itemId);
  487. $extraData = false;
  488. if (!empty($itemId)) {
  489. $extraData = $this->get_handler_extra_data($itemId);
  490. if ($form) {
  491. if (!empty($showOnlyTheseFields)) {
  492. $setData = [];
  493. foreach ($showOnlyTheseFields as $variable) {
  494. $extraName = 'extra_'.$variable;
  495. if (in_array($extraName, array_keys($extraData))) {
  496. $setData[$extraName] = $extraData[$extraName];
  497. }
  498. }
  499. $form->setDefaults($setData);
  500. } else {
  501. $form->setDefaults($extraData);
  502. }
  503. }
  504. }
  505. $conditions = [];
  506. if ($filter) {
  507. $conditions = ['filter = ?' => 1];
  508. }
  509. $extraFields = $this->get_all($conditions, 'option_order');
  510. $extra = $this->set_extra_fields_in_form(
  511. $form,
  512. $extraData,
  513. $adminPermissions,
  514. $extraFields,
  515. $itemId,
  516. $exclude,
  517. $useTagAsSelect,
  518. $showOnlyTheseFields,
  519. $orderFields,
  520. $orderDependingDefaults,
  521. $separateExtraMultipleSelect,
  522. $customLabelsExtraMultipleSelect,
  523. $addEmptyOptionSelects,
  524. $introductionTextList,
  525. $hideGeoLocalizationDetails,
  526. $help
  527. );
  528. if (!empty($requiredFields)) {
  529. /** @var HTML_QuickForm_input $element */
  530. foreach ($form->getElements() as $element) {
  531. $name = str_replace('extra_', '', $element->getName());
  532. if (in_array($name, $requiredFields)) {
  533. $form->setRequired($element);
  534. }
  535. }
  536. }
  537. return $extra;
  538. }
  539. /**
  540. * Return an array of all the extra fields available for this item.
  541. *
  542. * @param int $itemId (session_id, question_id, course id)
  543. *
  544. * @return array
  545. */
  546. public function get_handler_extra_data($itemId)
  547. {
  548. if (empty($itemId)) {
  549. return [];
  550. }
  551. $extra_data = [];
  552. $fields = $this->get_all();
  553. $field_values = new ExtraFieldValue($this->type);
  554. if (!empty($fields) > 0) {
  555. foreach ($fields as $field) {
  556. $field_value = $field_values->get_values_by_handler_and_field_id(
  557. $itemId,
  558. $field['id']
  559. );
  560. if ($field['field_type'] == self::FIELD_TYPE_TAG) {
  561. $tags = UserManager::get_user_tags_to_string(
  562. $itemId,
  563. $field['id'],
  564. false
  565. );
  566. $extra_data['extra_'.$field['variable']] = $tags;
  567. continue;
  568. }
  569. if ($field_value) {
  570. $variable = $field['variable'];
  571. $field_value = $field_value['value'];
  572. switch ($field['field_type']) {
  573. case self::FIELD_TYPE_TAG:
  574. $tags = UserManager::get_user_tags_to_string(
  575. $itemId,
  576. $field['id'],
  577. false
  578. );
  579. $extra_data['extra_'.$field['variable']] = $tags;
  580. break;
  581. case self::FIELD_TYPE_DOUBLE_SELECT:
  582. case self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  583. $selected_options = explode('::', $field_value);
  584. $firstOption = isset($selected_options[0]) ? $selected_options[0] : '';
  585. $secondOption = isset($selected_options[1]) ? $selected_options[1] : '';
  586. $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $firstOption;
  587. $extra_data['extra_'.$field['variable']]['extra_'.$field['variable'].'_second'] = $secondOption;
  588. break;
  589. case self::FIELD_TYPE_SELECT_MULTIPLE:
  590. $field_value = explode(';', $field_value);
  591. $extra_data['extra_'.$field['variable']] = $field_value;
  592. break;
  593. case self::FIELD_TYPE_RADIO:
  594. $extra_data['extra_'.$field['variable']]['extra_'.$field['variable']] = $field_value;
  595. break;
  596. case self::FIELD_TYPE_TRIPLE_SELECT:
  597. list($level1, $level2, $level3) = explode(';', $field_value);
  598. $extra_data["extra_$variable"]["extra_$variable"] = $level1;
  599. $extra_data["extra_$variable"]["extra_{$variable}_second"] = $level2;
  600. $extra_data["extra_$variable"]["extra_{$variable}_third"] = $level3;
  601. break;
  602. default:
  603. $extra_data['extra_'.$field['variable']] = $field_value;
  604. break;
  605. }
  606. } else {
  607. // Set default values
  608. if (isset($field['field_default_value']) &&
  609. !empty($field['field_default_value'])
  610. ) {
  611. $extra_data['extra_'.$field['variable']] = $field['field_default_value'];
  612. }
  613. }
  614. }
  615. }
  616. return $extra_data;
  617. }
  618. /**
  619. * @param string $field_type
  620. *
  621. * @return array
  622. */
  623. public function get_all_extra_field_by_type($field_type)
  624. {
  625. // all the information of the field
  626. $sql = "SELECT * FROM {$this->table}
  627. WHERE
  628. field_type = '".Database::escape_string($field_type)."' AND
  629. extra_field_type = $this->extraFieldType
  630. ";
  631. $result = Database::query($sql);
  632. $return = [];
  633. while ($row = Database::fetch_array($result)) {
  634. $return[] = $row['id'];
  635. }
  636. return $return;
  637. }
  638. /**
  639. * @return array
  640. */
  641. public function get_field_types()
  642. {
  643. return $this->get_extra_fields_by_handler($this->type);
  644. }
  645. /**
  646. * @param int $id
  647. */
  648. public function get_field_type_by_id($id)
  649. {
  650. $types = $this->get_field_types();
  651. if (isset($types[$id])) {
  652. return $types[$id];
  653. }
  654. return null;
  655. }
  656. /**
  657. * Converts a string like this:
  658. * France:Paris;Bretagne;Marseille;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
  659. * into
  660. * array(
  661. * 'France' =>
  662. * array('Paris', 'Bretagne', 'Marseille'),
  663. * 'Belgique' =>
  664. * array('Namur', 'Liège')
  665. * ), etc.
  666. *
  667. * @param string $string
  668. *
  669. * @return array
  670. */
  671. public static function extra_field_double_select_convert_string_to_array($string)
  672. {
  673. $options = explode('|', $string);
  674. $options_parsed = [];
  675. $id = 0;
  676. if (!empty($options)) {
  677. foreach ($options as $sub_options) {
  678. $options = explode(':', $sub_options);
  679. $sub_sub_options = isset($options[1]) ? explode(';', $options[1]) : [];
  680. $options_parsed[$id] = [
  681. 'label' => $options[0],
  682. 'options' => $sub_sub_options,
  683. ];
  684. $id++;
  685. }
  686. }
  687. return $options_parsed;
  688. }
  689. /**
  690. * @param $string
  691. *
  692. * @return array
  693. */
  694. public static function tripleSelectConvertStringToArray($string)
  695. {
  696. $options = [];
  697. foreach (explode('|', $string) as $i => $item0) {
  698. $level1 = explode('\\', $item0);
  699. foreach ($level1 as $j => $item1) {
  700. if (0 === $j) {
  701. $options[] = ['label' => $item1, 'options' => []];
  702. continue;
  703. }
  704. foreach (explode(':', $item1) as $k => $item2) {
  705. if (0 === $k) {
  706. $options[$i]['options'][] = ['label' => $item2, 'options' => []];
  707. continue;
  708. }
  709. $options[$i]['options'][$j - 1]['options'][] = explode(';', $item2);
  710. }
  711. }
  712. }
  713. array_walk_recursive($options, function (&$item) {
  714. $item = trim($item);
  715. });
  716. return $options;
  717. }
  718. /**
  719. * @param array $options
  720. *
  721. * @return array
  722. */
  723. public static function extra_field_double_select_convert_array_to_ordered_array($options)
  724. {
  725. $options_parsed = [];
  726. if (!empty($options)) {
  727. foreach ($options as $option) {
  728. if ($option['option_value'] == 0) {
  729. $options_parsed[$option['id']][] = $option;
  730. } else {
  731. $options_parsed[$option['option_value']][] = $option;
  732. }
  733. }
  734. }
  735. return $options_parsed;
  736. }
  737. /**
  738. * @param array $options
  739. *
  740. * @return array
  741. */
  742. public static function tripleSelectConvertArrayToOrderedArray(array $options)
  743. {
  744. $level1 = self::getOptionsFromTripleSelect($options, 0);
  745. $level2 = [];
  746. $level3 = [];
  747. foreach ($level1 as $item1) {
  748. $level2 += self::getOptionsFromTripleSelect($options, $item1['id']);
  749. }
  750. foreach ($level2 as $item2) {
  751. $level3 += self::getOptionsFromTripleSelect($options, $item2['id']);
  752. }
  753. return ['level1' => $level1, 'level2' => $level2, 'level3' => $level3];
  754. }
  755. /**
  756. * @param array $options the result of the get_field_options_by_field() array
  757. *
  758. * @return string
  759. */
  760. public static function extra_field_double_select_convert_array_to_string($options)
  761. {
  762. $string = null;
  763. $options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
  764. if (!empty($options_parsed)) {
  765. foreach ($options_parsed as $option) {
  766. foreach ($option as $key => $item) {
  767. $string .= $item['display_text'];
  768. if ($key == 0) {
  769. $string .= ':';
  770. } else {
  771. if (isset($option[$key + 1])) {
  772. $string .= ';';
  773. }
  774. }
  775. }
  776. $string .= '|';
  777. }
  778. }
  779. if (!empty($string)) {
  780. $string = substr($string, 0, strlen($string) - 1);
  781. }
  782. return $string;
  783. }
  784. /**
  785. * @param array $options The result of the get_field_options_by_field() array
  786. *
  787. * @return string
  788. */
  789. public static function extraFieldSelectWithTextConvertArrayToString(array $options)
  790. {
  791. $string = '';
  792. $parsedOptions = self::extra_field_double_select_convert_array_to_ordered_array($options);
  793. if (empty($parsedOptions)) {
  794. return '';
  795. }
  796. foreach ($parsedOptions as $options) {
  797. $option = current($options);
  798. $string .= $option['display_text'];
  799. $string .= '|';
  800. }
  801. return rtrim($string, '|');
  802. }
  803. /**
  804. * @param array $options
  805. *
  806. * @return string
  807. */
  808. public static function tripleSelectConvertArrayToString(array $options)
  809. {
  810. $string = '';
  811. $parsedOptions = self::tripleSelectConvertArrayToOrderedArray($options);
  812. foreach ($parsedOptions['level1'] as $item1) {
  813. $string .= $item1['display_text'];
  814. $level2 = self::getOptionsFromTripleSelect($parsedOptions['level2'], $item1['id']);
  815. foreach ($level2 as $item2) {
  816. $string .= '\\'.$item2['display_text'].':';
  817. $level3 = self::getOptionsFromTripleSelect($parsedOptions['level3'], $item2['id']);
  818. $string .= implode(';', array_column($level3, 'display_text'));
  819. }
  820. $string .= '|';
  821. }
  822. return trim($string, '\\|;');
  823. }
  824. /**
  825. * @param array $params
  826. *
  827. * @return array
  828. */
  829. public function clean_parameters($params)
  830. {
  831. if (!isset($params['variable']) || empty($params['variable'])) {
  832. $params['variable'] = $params['display_text'];
  833. }
  834. $params['variable'] = trim(strtolower(str_replace(" ", "_", $params['variable'])));
  835. if (!isset($params['field_order'])) {
  836. $max_order = self::get_max_field_order();
  837. $params['field_order'] = $max_order;
  838. } else {
  839. $params['field_order'] = (int) $params['field_order'];
  840. }
  841. return $params;
  842. }
  843. /**
  844. * @param array $params
  845. * @param bool $show_query
  846. *
  847. * @return int|bool
  848. */
  849. public function save($params, $show_query = false)
  850. {
  851. $fieldInfo = self::get_handler_field_info_by_field_variable($params['variable']);
  852. $params = $this->clean_parameters($params);
  853. $params['extra_field_type'] = $this->extraFieldType;
  854. if ($fieldInfo) {
  855. return $fieldInfo['id'];
  856. } else {
  857. $id = parent::save($params, $show_query);
  858. if ($id) {
  859. $fieldOption = new ExtraFieldOption($this->type);
  860. $params['field_id'] = $id;
  861. $fieldOption->save($params);
  862. }
  863. return $id;
  864. }
  865. }
  866. /**
  867. * {@inheritdoc}
  868. */
  869. public function update($params, $showQuery = false)
  870. {
  871. $params = $this->clean_parameters($params);
  872. if (isset($params['id'])) {
  873. $fieldOption = new ExtraFieldOption($this->type);
  874. $params['field_id'] = $params['id'];
  875. if (empty($params['field_type'])) {
  876. $params['field_type'] = $this->type;
  877. }
  878. $fieldOption->save($params, $showQuery);
  879. }
  880. return parent::update($params, $showQuery);
  881. }
  882. /**
  883. * @param $id
  884. *
  885. * @return bool
  886. */
  887. public function delete($id)
  888. {
  889. $em = Database::getManager();
  890. $items = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findBy(['field' => $id]);
  891. if ($items) {
  892. foreach ($items as $item) {
  893. $em->remove($item);
  894. }
  895. $em->flush();
  896. }
  897. $field_option = new ExtraFieldOption($this->type);
  898. $field_option->delete_all_options_by_field_id($id);
  899. $session_field_values = new ExtraFieldValue($this->type);
  900. $session_field_values->delete_all_values_by_field_id($id);
  901. return parent::delete($id);
  902. }
  903. /**
  904. * Add an element that matches the given extra field to the given $form object.
  905. *
  906. * @param FormValidator $form The form these fields are to be attached to
  907. * @param array $extraData
  908. * @param bool $adminPermissions Whether the display is considered without edition limits (true) or not (false)
  909. * @param array $extra
  910. * @param int $itemId The item (course, user, session, etc) this extra_field is attached to
  911. * @param array $exclude Extra fields to be skipped, by textual ID
  912. * @param bool $useTagAsSelect Whether to show tag fields as select drop-down or not
  913. * @param array $showOnlyTheseFields Limit the extra fields shown to just the list given here
  914. * @param array $orderFields An array containing the names of the fields shown, in the right order
  915. *
  916. * @throws Exception
  917. *
  918. * @return array If relevant, returns a one-element array with JS code to be added to the page HTML headers
  919. */
  920. public function set_extra_fields_in_form(
  921. $form,
  922. $extraData,
  923. $adminPermissions = false,
  924. $extra = [],
  925. $itemId = null,
  926. $exclude = [],
  927. $useTagAsSelect = false,
  928. $showOnlyTheseFields = [],
  929. $orderFields = [],
  930. $orderDependingDefaults = false,
  931. $separateExtraMultipleSelect = [],
  932. $customLabelsExtraMultipleSelect = [],
  933. $addEmptyOptionSelects = false,
  934. $introductionTextList = [],
  935. $hideGeoLocalizationDetails = false,
  936. $help = false
  937. ) {
  938. $jquery_ready_content = null;
  939. if (!empty($extra)) {
  940. $newOrder = [];
  941. if (!empty($orderFields)) {
  942. foreach ($orderFields as $order) {
  943. foreach ($extra as $field_details) {
  944. if ($order == $field_details['variable']) {
  945. $newOrder[] = $field_details;
  946. }
  947. }
  948. }
  949. $extra = $newOrder;
  950. }
  951. foreach ($extra as $field_details) {
  952. if (!empty($showOnlyTheseFields)) {
  953. if (!in_array($field_details['variable'], $showOnlyTheseFields)) {
  954. continue;
  955. }
  956. }
  957. // Getting default value id if is set
  958. $defaultValueId = null;
  959. if (isset($field_details['options']) && !empty($field_details['options'])) {
  960. $valueToFind = null;
  961. if (isset($field_details['field_default_value'])) {
  962. $valueToFind = $field_details['field_default_value'];
  963. }
  964. // If a value is found we override the default value
  965. if (isset($extraData['extra_'.$field_details['variable']])) {
  966. $valueToFind = $extraData['extra_'.$field_details['variable']];
  967. }
  968. foreach ($field_details['options'] as $option) {
  969. if ($option['option_value'] == $valueToFind) {
  970. $defaultValueId = $option['id'];
  971. }
  972. }
  973. }
  974. if (!$adminPermissions) {
  975. if ($field_details['visible_to_self'] == 0) {
  976. continue;
  977. }
  978. if (in_array($field_details['variable'], $exclude)) {
  979. continue;
  980. }
  981. }
  982. if (!empty($introductionTextList) &&
  983. in_array($field_details['variable'], array_keys($introductionTextList))
  984. ) {
  985. $form->addHtml($introductionTextList[$field_details['variable']]);
  986. }
  987. $freezeElement = false;
  988. if (!$adminPermissions) {
  989. $freezeElement = $field_details['visible_to_self'] == 0 || $field_details['changeable'] == 0;
  990. }
  991. $translatedDisplayText = get_lang($field_details['display_text'], true);
  992. $translatedDisplayHelpText = '';
  993. if ($help) {
  994. $translatedDisplayHelpText .= get_lang($field_details['display_text'].'Help');
  995. }
  996. if (!empty($translatedDisplayText)) {
  997. if (!empty($translatedDisplayHelpText)) {
  998. // In this case, exceptionally, display_text is an array
  999. // which is then treated by display_form()
  1000. $field_details['display_text'] = [$translatedDisplayText, $translatedDisplayHelpText];
  1001. } else {
  1002. // We have an helper text, use it
  1003. $field_details['display_text'] = $translatedDisplayText;
  1004. }
  1005. }
  1006. switch ($field_details['field_type']) {
  1007. case self::FIELD_TYPE_TEXT:
  1008. $form->addElement(
  1009. 'text',
  1010. 'extra_'.$field_details['variable'],
  1011. $field_details['display_text'],
  1012. [
  1013. 'id' => 'extra_'.$field_details['variable'],
  1014. ]
  1015. );
  1016. $form->applyFilter(
  1017. 'extra_'.$field_details['variable'],
  1018. 'stripslashes'
  1019. );
  1020. $form->applyFilter(
  1021. 'extra_'.$field_details['variable'],
  1022. 'trim'
  1023. );
  1024. if ($freezeElement) {
  1025. $form->freeze('extra_'.$field_details['variable']);
  1026. }
  1027. break;
  1028. case self::FIELD_TYPE_TEXTAREA:
  1029. $form->addHtmlEditor(
  1030. 'extra_'.$field_details['variable'],
  1031. $field_details['display_text'],
  1032. false,
  1033. false,
  1034. [
  1035. 'ToolbarSet' => 'Profile',
  1036. 'Width' => '100%',
  1037. 'Height' => '130',
  1038. 'id' => 'extra_'.$field_details['variable'],
  1039. ]
  1040. );
  1041. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1042. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1043. if ($freezeElement) {
  1044. $form->freeze('extra_'.$field_details['variable']);
  1045. }
  1046. break;
  1047. case self::FIELD_TYPE_RADIO:
  1048. $group = [];
  1049. if (isset($field_details['options']) &&
  1050. !empty($field_details['options'])
  1051. ) {
  1052. foreach ($field_details['options'] as $option_details) {
  1053. $options[$option_details['option_value']] = $option_details['display_text'];
  1054. $group[] = $form->createElement(
  1055. 'radio',
  1056. 'extra_'.$field_details['variable'],
  1057. $option_details['option_value'],
  1058. $option_details['display_text'].'<br />',
  1059. $option_details['option_value']
  1060. );
  1061. }
  1062. }
  1063. $form->addGroup(
  1064. $group,
  1065. 'extra_'.$field_details['variable'],
  1066. $field_details['display_text']
  1067. );
  1068. if ($freezeElement) {
  1069. $form->freeze('extra_'.$field_details['variable']);
  1070. }
  1071. break;
  1072. case self::FIELD_TYPE_CHECKBOX:
  1073. $group = [];
  1074. if (isset($field_details['options']) &&
  1075. !empty($field_details['options'])
  1076. ) {
  1077. foreach ($field_details['options'] as $option_details) {
  1078. $options[$option_details['option_value']] = $option_details['display_text'];
  1079. $group[] = $form->createElement(
  1080. 'checkbox',
  1081. 'extra_'.$field_details['variable'],
  1082. $option_details['option_value'],
  1083. $option_details['display_text'].'<br />',
  1084. $option_details['option_value']
  1085. );
  1086. }
  1087. } else {
  1088. $fieldVariable = "extra_{$field_details['variable']}";
  1089. $checkboxAttributes = [];
  1090. if (is_array($extraData) &&
  1091. array_key_exists($fieldVariable, $extraData)
  1092. ) {
  1093. if (!empty($extraData[$fieldVariable])) {
  1094. $checkboxAttributes['checked'] = 1;
  1095. }
  1096. }
  1097. if (empty($checkboxAttributes) &&
  1098. isset($field_details['default_value']) && empty($extraData)) {
  1099. if ($field_details['default_value'] == 1) {
  1100. $checkboxAttributes['checked'] = 1;
  1101. }
  1102. }
  1103. // We assume that is a switch on/off with 1 and 0 as values
  1104. $group[] = $form->createElement(
  1105. 'checkbox',
  1106. 'extra_'.$field_details['variable'],
  1107. null,
  1108. //$field_details['display_text'].'<br />',
  1109. get_lang('Yes'),
  1110. $checkboxAttributes
  1111. );
  1112. }
  1113. $form->addGroup(
  1114. $group,
  1115. 'extra_'.$field_details['variable'],
  1116. $field_details['display_text']
  1117. );
  1118. if ($freezeElement) {
  1119. $form->freeze('extra_'.$field_details['variable']);
  1120. }
  1121. break;
  1122. case self::FIELD_TYPE_SELECT:
  1123. $this->addSelectElement($form, $field_details, $defaultValueId, $freezeElement);
  1124. break;
  1125. case self::FIELD_TYPE_SELECT_MULTIPLE:
  1126. $options = [];
  1127. if (empty($defaultValueId)) {
  1128. $options[''] = get_lang('SelectAnOption');
  1129. }
  1130. foreach ($field_details['options'] as $optionDetails) {
  1131. $options[$optionDetails['option_value']] = $optionDetails['display_text'];
  1132. }
  1133. $form->addElement(
  1134. 'select',
  1135. 'extra_'.$field_details['variable'],
  1136. $field_details['display_text'],
  1137. $options,
  1138. [
  1139. 'multiple' => 'multiple',
  1140. 'id' => 'extra_'.$field_details['variable'],
  1141. ]
  1142. );
  1143. if ($freezeElement) {
  1144. $form->freeze('extra_'.$field_details['variable']);
  1145. }
  1146. break;
  1147. case self::FIELD_TYPE_DATE:
  1148. $form->addDatePicker('extra_'.$field_details['variable'], $field_details['display_text']);
  1149. if ($freezeElement) {
  1150. $form->freeze('extra_'.$field_details['variable']);
  1151. }
  1152. break;
  1153. case self::FIELD_TYPE_DATETIME:
  1154. $form->addDateTimePicker(
  1155. 'extra_'.$field_details['variable'],
  1156. $field_details['display_text']
  1157. );
  1158. $defaults['extra_'.$field_details['variable']] = api_get_local_time();
  1159. if (!isset($form->_defaultValues['extra_'.$field_details['variable']])) {
  1160. $form->setDefaults($defaults);
  1161. }
  1162. if ($freezeElement) {
  1163. $form->freeze('extra_'.$field_details['variable']);
  1164. }
  1165. break;
  1166. case self::FIELD_TYPE_DOUBLE_SELECT:
  1167. $jquery_ready_content .= self::addDoubleSelectElement(
  1168. $form,
  1169. $field_details,
  1170. $extraData,
  1171. $freezeElement
  1172. );
  1173. break;
  1174. case self::FIELD_TYPE_DIVIDER:
  1175. $form->addHtml('
  1176. <div class="form-group ">
  1177. <div class="col-sm-12">
  1178. <div class="panel-separator">
  1179. <h4 id="'.$field_details['variable'].'" class="form-separator">'
  1180. .$field_details['display_text'].'
  1181. </h4>
  1182. </div>
  1183. </div>
  1184. </div>
  1185. ');
  1186. break;
  1187. case self::FIELD_TYPE_TAG:
  1188. $variable = $field_details['variable'];
  1189. $field_id = $field_details['id'];
  1190. $separateValue = 0;
  1191. if (isset($separateExtraMultipleSelect[$field_details['variable']])) {
  1192. $separateValue = $separateExtraMultipleSelect[$field_details['variable']];
  1193. }
  1194. $selectedOptions = [];
  1195. if ($separateValue > 0) {
  1196. $em = Database::getManager();
  1197. $fieldTags = $em
  1198. ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  1199. ->findBy(
  1200. [
  1201. 'fieldId' => $field_id,
  1202. 'itemId' => $itemId,
  1203. ]
  1204. );
  1205. // ofaj
  1206. for ($i = 0; $i < $separateValue; $i++) {
  1207. $tagsSelect = $form->addElement(
  1208. 'select',
  1209. 'extra_'.$field_details['variable'].'['.$i.']',
  1210. $customLabelsExtraMultipleSelect[$field_details['variable']][$i], //$field_details['display_text'],
  1211. null,
  1212. ['id' => 'extra_'.$field_details['variable'].'_'.$i]
  1213. );
  1214. if ($addEmptyOptionSelects) {
  1215. $tagsSelect->addOption(
  1216. '',
  1217. ''
  1218. );
  1219. }
  1220. foreach ($fieldTags as $fieldTag) {
  1221. $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
  1222. if (empty($tag)) {
  1223. continue;
  1224. }
  1225. $tagsSelect->addOption(
  1226. $tag->getTag(),
  1227. $tag->getTag()
  1228. );
  1229. }
  1230. }
  1231. } else {
  1232. $tagsSelect = $form->addSelect(
  1233. "extra_{$field_details['variable']}",
  1234. $field_details['display_text'],
  1235. [],
  1236. ['style' => 'width: 100%;']
  1237. );
  1238. if ($useTagAsSelect === false) {
  1239. $tagsSelect->setAttribute('class', null);
  1240. }
  1241. $tagsSelect->setAttribute(
  1242. 'id',
  1243. "extra_{$field_details['variable']}"
  1244. );
  1245. $tagsSelect->setMultiple(true);
  1246. $selectedOptions = [];
  1247. if ($this->type === 'user') {
  1248. // The magic should be here
  1249. $user_tags = UserManager::get_user_tags(
  1250. $itemId,
  1251. $field_details['id']
  1252. );
  1253. if (is_array($user_tags) && count($user_tags) > 0) {
  1254. foreach ($user_tags as $tag) {
  1255. if (empty($tag['tag'])) {
  1256. continue;
  1257. }
  1258. $tagsSelect->addOption(
  1259. $tag['tag'],
  1260. $tag['tag'],
  1261. [
  1262. 'selected' => 'selected',
  1263. 'class' => 'selected',
  1264. ]
  1265. );
  1266. $selectedOptions[] = $tag['tag'];
  1267. }
  1268. }
  1269. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
  1270. } else {
  1271. $em = Database::getManager();
  1272. $fieldTags = $em->getRepository(
  1273. 'ChamiloCoreBundle:ExtraFieldRelTag'
  1274. )
  1275. ->findBy(
  1276. [
  1277. 'fieldId' => $field_id,
  1278. 'itemId' => $itemId,
  1279. ]
  1280. );
  1281. /** @var ExtraFieldRelTag $fieldTag */
  1282. foreach ($fieldTags as $fieldTag) {
  1283. /** @var Tag $tag */
  1284. $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
  1285. if (empty($tag)) {
  1286. continue;
  1287. }
  1288. $tagsSelect->addOption(
  1289. $tag->getTag(),
  1290. $tag->getTag()
  1291. );
  1292. $selectedOptions[] = $tag->getTag();
  1293. }
  1294. if (!empty($extraData) && isset($extraData['extra_'.$field_details['variable']])) {
  1295. $data = $extraData['extra_'.$field_details['variable']];
  1296. if (!empty($data)) {
  1297. foreach ($data as $option) {
  1298. $tagsSelect->addOption(
  1299. $option,
  1300. $option
  1301. );
  1302. }
  1303. }
  1304. }
  1305. if ($useTagAsSelect) {
  1306. $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  1307. ->findBy(
  1308. [
  1309. 'fieldId' => $field_id,
  1310. ]
  1311. );
  1312. $tagsAdded = [];
  1313. foreach ($fieldTags as $fieldTag) {
  1314. $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId());
  1315. if (empty($tag)) {
  1316. continue;
  1317. }
  1318. $tagText = $tag->getTag();
  1319. if (in_array($tagText, $tagsAdded)) {
  1320. continue;
  1321. }
  1322. $tagsSelect->addOption(
  1323. $tag->getTag(),
  1324. $tag->getTag(),
  1325. []
  1326. );
  1327. $tagsAdded[] = $tagText;
  1328. }
  1329. }
  1330. $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php';
  1331. }
  1332. $form->setDefaults(
  1333. [
  1334. 'extra_'.$field_details['variable'] => $selectedOptions,
  1335. ]
  1336. );
  1337. if ($useTagAsSelect == false) {
  1338. $jquery_ready_content .= "
  1339. $('#extra_$variable').select2({
  1340. ajax: {
  1341. url: '$url?a=search_tags&field_id=$field_id&type={$this->type}',
  1342. processResults: function (data) {
  1343. return {
  1344. results: data.items
  1345. }
  1346. }
  1347. },
  1348. cache: false,
  1349. tags: true,
  1350. tokenSeparators: [','],
  1351. placeholder: '".get_lang('StartToType')."'
  1352. });
  1353. ";
  1354. }
  1355. }
  1356. break;
  1357. case self::FIELD_TYPE_TIMEZONE:
  1358. $form->addElement(
  1359. 'select',
  1360. 'extra_'.$field_details['variable'],
  1361. $field_details['display_text'],
  1362. api_get_timezones(),
  1363. ''
  1364. );
  1365. if ($freezeElement) {
  1366. $form->freeze('extra_'.$field_details['variable']);
  1367. }
  1368. break;
  1369. case self::FIELD_TYPE_SOCIAL_PROFILE:
  1370. // get the social network's favicon
  1371. $extra_data_variable = isset($extraData['extra_'.$field_details['variable']])
  1372. ? $extraData['extra_'.$field_details['variable']]
  1373. : null;
  1374. $field_default_value = isset($field_details['field_default_value'])
  1375. ? $field_details['field_default_value']
  1376. : null;
  1377. $icon_path = UserManager::get_favicon_from_url(
  1378. $extra_data_variable,
  1379. $field_default_value
  1380. );
  1381. // special hack for hi5
  1382. $leftpad = '1.7';
  1383. $top = '0.4';
  1384. $domain = parse_url($icon_path, PHP_URL_HOST);
  1385. if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
  1386. $leftpad = '3';
  1387. $top = '0';
  1388. }
  1389. // print the input field
  1390. $form->addElement(
  1391. 'text',
  1392. 'extra_'.$field_details['variable'],
  1393. $field_details['display_text'],
  1394. [
  1395. 'size' => 60,
  1396. 'size' => implode(
  1397. '; ',
  1398. [
  1399. "background-image: url('$icon_path')",
  1400. 'background-repeat: no-repeat',
  1401. "background-position: 0.4em {$top}em",
  1402. "padding-left: {$leftpad}em",
  1403. ]
  1404. ),
  1405. ]
  1406. );
  1407. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1408. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1409. if ($freezeElement) {
  1410. $form->freeze('extra_'.$field_details['variable']);
  1411. }
  1412. break;
  1413. case self::FIELD_TYPE_MOBILE_PHONE_NUMBER:
  1414. $form->addElement(
  1415. 'text',
  1416. 'extra_'.$field_details['variable'],
  1417. $field_details['display_text']." (".get_lang('CountryDialCode').")",
  1418. ['size' => 40, 'placeholder' => '(xx)xxxxxxxxx']
  1419. );
  1420. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1421. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1422. $form->applyFilter('extra_'.$field_details['variable'], 'mobile_phone_number_filter');
  1423. $form->addRule(
  1424. 'extra_'.$field_details['variable'],
  1425. get_lang('MobilePhoneNumberWrong'),
  1426. 'mobile_phone_number'
  1427. );
  1428. if ($freezeElement) {
  1429. $form->freeze('extra_'.$field_details['variable']);
  1430. }
  1431. break;
  1432. case self::FIELD_TYPE_INTEGER:
  1433. $form->addElement(
  1434. 'number',
  1435. 'extra_'.$field_details['variable'],
  1436. $field_details['display_text'],
  1437. ['class' => 'span1', 'step' => 1]
  1438. );
  1439. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1440. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1441. $form->applyFilter('extra_'.$field_details['variable'], 'intval');
  1442. if ($freezeElement) {
  1443. $form->freeze('extra_'.$field_details['variable']);
  1444. }
  1445. break;
  1446. case self::FIELD_TYPE_FILE_IMAGE:
  1447. $fieldVariable = "extra_{$field_details['variable']}";
  1448. $fieldTexts = [
  1449. $field_details['display_text'],
  1450. ];
  1451. if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
  1452. if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
  1453. $fieldTexts[] = Display::img(
  1454. api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
  1455. $field_details['display_text'],
  1456. ['width' => '300']
  1457. );
  1458. }
  1459. }
  1460. if ($fieldTexts[0] === 'Image') {
  1461. $fieldTexts[0] = get_lang($fieldTexts[0]);
  1462. }
  1463. $form->addFile(
  1464. $fieldVariable,
  1465. $fieldTexts,
  1466. ['accept' => 'image/*', 'id' => 'extra_image', 'crop_image' => 'true']
  1467. );
  1468. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1469. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1470. $allowedPictureTypes = ['jpg', 'jpeg', 'png', 'gif'];
  1471. $form->addRule(
  1472. 'extra_'.$field_details['variable'],
  1473. get_lang('OnlyImagesAllowed').' ('.implode(',', $allowedPictureTypes).')',
  1474. 'filetype',
  1475. $allowedPictureTypes
  1476. );
  1477. if ($freezeElement) {
  1478. $form->freeze('extra_'.$field_details['variable']);
  1479. }
  1480. break;
  1481. case self::FIELD_TYPE_FLOAT:
  1482. $form->addElement(
  1483. 'number',
  1484. 'extra_'.$field_details['variable'],
  1485. $field_details['display_text'],
  1486. ['class' => 'span1', 'step' => '0.01']
  1487. );
  1488. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1489. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1490. $form->applyFilter('extra_'.$field_details['variable'], 'floatval');
  1491. if ($freezeElement) {
  1492. $form->freeze('extra_'.$field_details['variable']);
  1493. }
  1494. break;
  1495. case self::FIELD_TYPE_FILE:
  1496. $fieldVariable = "extra_{$field_details['variable']}";
  1497. $fieldTexts = [
  1498. $field_details['display_text'],
  1499. ];
  1500. if (is_array($extraData) &&
  1501. array_key_exists($fieldVariable, $extraData)
  1502. ) {
  1503. if (file_exists(api_get_path(SYS_UPLOAD_PATH).$extraData[$fieldVariable])) {
  1504. $linkToDelete = '';
  1505. $divItemId = $field_details['variable'];
  1506. if (api_is_platform_admin()) {
  1507. $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?type='.$this->type;
  1508. $url .= '&a=delete_file&field_id='.$field_details['id'].'&item_id='.$itemId;
  1509. $deleteId = $field_details['variable'].'_delete';
  1510. $form->addHtml("
  1511. <script>
  1512. $(function() {
  1513. $('#".$deleteId."').on('click', function() {
  1514. $.ajax({
  1515. type: 'GET',
  1516. url: '".$url."',
  1517. success: function(result) {
  1518. if (result == 1) {
  1519. $('#".$divItemId."').html('".get_lang('Deleted')."');
  1520. }
  1521. }
  1522. });
  1523. });
  1524. });
  1525. </script>
  1526. ");
  1527. $linkToDelete = '&nbsp;'.Display::url(
  1528. Display::return_icon('delete.png', get_lang('Delete')),
  1529. 'javascript:void(0)',
  1530. ['id' => $deleteId]
  1531. );
  1532. }
  1533. $fieldTexts[] = '<div id="'.$divItemId.'">'.Display::url(
  1534. basename($extraData[$fieldVariable]),
  1535. api_get_path(WEB_UPLOAD_PATH).$extraData[$fieldVariable],
  1536. [
  1537. 'title' => $field_details['display_text'],
  1538. 'target' => '_blank',
  1539. ]
  1540. ).$linkToDelete.'</div>';
  1541. }
  1542. }
  1543. $form->addElement(
  1544. 'file',
  1545. $fieldVariable,
  1546. $fieldTexts,
  1547. []
  1548. );
  1549. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1550. $form->applyFilter('extra_'.$field_details['variable'], 'trim');
  1551. if ($freezeElement) {
  1552. $form->freeze('extra_'.$field_details['variable']);
  1553. }
  1554. break;
  1555. case self::FIELD_TYPE_VIDEO_URL:
  1556. $form->addUrl(
  1557. "extra_{$field_details['variable']}",
  1558. $field_details['display_text'],
  1559. false,
  1560. ['placeholder' => 'https://']
  1561. );
  1562. if ($freezeElement) {
  1563. $form->freeze('extra_'.$field_details['variable']);
  1564. }
  1565. break;
  1566. case self::FIELD_TYPE_LETTERS_ONLY:
  1567. $form->addTextLettersOnly(
  1568. "extra_{$field_details['variable']}",
  1569. $field_details['display_text']
  1570. );
  1571. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1572. if ($freezeElement) {
  1573. $form->freeze('extra_'.$field_details['variable']);
  1574. }
  1575. break;
  1576. case self::FIELD_TYPE_ALPHANUMERIC:
  1577. $form->addTextAlphanumeric(
  1578. "extra_{$field_details['variable']}",
  1579. $field_details['display_text']
  1580. );
  1581. $form->applyFilter(
  1582. 'extra_'.$field_details['variable'],
  1583. 'stripslashes'
  1584. );
  1585. if ($freezeElement) {
  1586. $form->freeze('extra_'.$field_details['variable']);
  1587. }
  1588. break;
  1589. case self::FIELD_TYPE_LETTERS_SPACE:
  1590. $form->addTextLettersAndSpaces(
  1591. "extra_{$field_details['variable']}",
  1592. $field_details['display_text']
  1593. );
  1594. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1595. if ($freezeElement) {
  1596. $form->freeze('extra_'.$field_details['variable']);
  1597. }
  1598. break;
  1599. case self::FIELD_TYPE_ALPHANUMERIC_SPACE:
  1600. $form->addTextAlphanumericAndSpaces(
  1601. "extra_{$field_details['variable']}",
  1602. $field_details['display_text']
  1603. );
  1604. $form->applyFilter(
  1605. 'extra_'.$field_details['variable'],
  1606. 'stripslashes'
  1607. );
  1608. if ($freezeElement) {
  1609. $form->freeze('extra_'.$field_details['variable']);
  1610. }
  1611. break;
  1612. case self::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
  1613. case self::FIELD_TYPE_GEOLOCALIZATION:
  1614. $dataValue = isset($extraData['extra_'.$field_details['variable']])
  1615. ? $extraData['extra_'.$field_details['variable']]
  1616. : '';
  1617. $form->addGeoLocationMapField(
  1618. 'extra_'.$field_details['variable'],
  1619. $field_details['display_text'],
  1620. $dataValue,
  1621. $hideGeoLocalizationDetails
  1622. );
  1623. /*$form->addElement(
  1624. 'text',
  1625. 'extra_'.$field_details['variable'],
  1626. $field_details['display_text'],
  1627. ['id' => 'extra_'.$field_details['variable']]
  1628. );
  1629. $form->addHidden(
  1630. 'extra_'.$field_details['variable'].'_coordinates',
  1631. '',
  1632. ['id' => 'extra_'.$field_details['variable'].'_coordinates']
  1633. );
  1634. $form->applyFilter('extra_'.$field_details['variable'], 'stripslashes');
  1635. $form->applyFilter('extra_'.$field_details['variable'], 'trim');*/
  1636. if ($freezeElement) {
  1637. $form->freeze('extra_'.$field_details['variable']);
  1638. }
  1639. break;
  1640. case self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  1641. $jquery_ready_content .= $this->addSelectWithTextFieldElement(
  1642. $form,
  1643. $field_details,
  1644. $freezeElement
  1645. );
  1646. break;
  1647. case self::FIELD_TYPE_TRIPLE_SELECT:
  1648. $jquery_ready_content .= $this->addTripleSelectElement(
  1649. $form,
  1650. $field_details,
  1651. is_array($extraData) ? $extraData : [],
  1652. $freezeElement
  1653. );
  1654. break;
  1655. }
  1656. }
  1657. }
  1658. $return = [];
  1659. $return['jquery_ready_content'] = $jquery_ready_content;
  1660. return $return;
  1661. }
  1662. /**
  1663. * @param $breadcrumb
  1664. * @param $action
  1665. */
  1666. public function setupBreadcrumb(&$breadcrumb, $action)
  1667. {
  1668. if ($action == 'add') {
  1669. $breadcrumb[] = ['url' => $this->pageUrl, 'name' => $this->pageName];
  1670. $breadcrumb[] = ['url' => '#', 'name' => get_lang('Add')];
  1671. } elseif ($action == 'edit') {
  1672. $breadcrumb[] = ['url' => $this->pageUrl, 'name' => $this->pageName];
  1673. $breadcrumb[] = ['url' => '#', 'name' => get_lang('Edit')];
  1674. } else {
  1675. $breadcrumb[] = ['url' => '#', 'name' => $this->pageName];
  1676. }
  1677. }
  1678. /**
  1679. * Displays the title + grid.
  1680. */
  1681. public function display()
  1682. {
  1683. // action links
  1684. echo '<div class="actions">';
  1685. echo '<a href="../admin/index.php">';
  1686. echo Display::return_icon(
  1687. 'back.png',
  1688. get_lang('BackTo').' '.get_lang('PlatformAdmin'),
  1689. '',
  1690. ICON_SIZE_MEDIUM
  1691. );
  1692. echo '</a>';
  1693. echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'">';
  1694. echo Display::return_icon(
  1695. 'add_user_fields.png',
  1696. get_lang('Add'),
  1697. '',
  1698. ICON_SIZE_MEDIUM
  1699. );
  1700. echo '</a>';
  1701. echo '</div>';
  1702. echo Display::grid_html($this->type.'_fields');
  1703. }
  1704. /**
  1705. * @return array
  1706. */
  1707. public function getJqgridColumnNames()
  1708. {
  1709. return [
  1710. get_lang('Name'),
  1711. get_lang('FieldLabel'),
  1712. get_lang('Type'),
  1713. get_lang('FieldChangeability'),
  1714. get_lang('VisibleToSelf'),
  1715. get_lang('VisibleToOthers'),
  1716. get_lang('Filter'),
  1717. get_lang('FieldOrder'),
  1718. get_lang('Actions'),
  1719. ];
  1720. }
  1721. /**
  1722. * @return array
  1723. */
  1724. public function getJqgridColumnModel()
  1725. {
  1726. return [
  1727. [
  1728. 'name' => 'display_text',
  1729. 'index' => 'display_text',
  1730. 'width' => '140',
  1731. 'align' => 'left',
  1732. ],
  1733. [
  1734. 'name' => 'variable',
  1735. 'index' => 'variable',
  1736. 'width' => '90',
  1737. 'align' => 'left',
  1738. 'sortable' => 'true',
  1739. ],
  1740. [
  1741. 'name' => 'field_type',
  1742. 'index' => 'field_type',
  1743. 'width' => '70',
  1744. 'align' => 'left',
  1745. 'sortable' => 'true',
  1746. ],
  1747. [
  1748. 'name' => 'changeable',
  1749. 'index' => 'changeable',
  1750. 'width' => '35',
  1751. 'align' => 'left',
  1752. 'sortable' => 'true',
  1753. ],
  1754. [
  1755. 'name' => 'visible_to_self',
  1756. 'index' => 'visible_to_self',
  1757. 'width' => '45',
  1758. 'align' => 'left',
  1759. 'sortable' => 'true',
  1760. ],
  1761. [
  1762. 'name' => 'visible_to_others',
  1763. 'index' => 'visible_to_others',
  1764. 'width' => '35',
  1765. 'align' => 'left',
  1766. 'sortable' => 'true',
  1767. ],
  1768. [
  1769. 'name' => 'filter',
  1770. 'index' => 'filter',
  1771. 'width' => '30',
  1772. 'align' => 'left',
  1773. 'sortable' => 'true',
  1774. ],
  1775. [
  1776. 'name' => 'field_order',
  1777. 'index' => 'field_order',
  1778. 'width' => '25',
  1779. 'align' => 'left',
  1780. 'sortable' => 'true',
  1781. ],
  1782. [
  1783. 'name' => 'actions',
  1784. 'index' => 'actions',
  1785. 'width' => '40',
  1786. 'align' => 'left',
  1787. 'formatter' => 'action_formatter',
  1788. 'sortable' => 'false',
  1789. ],
  1790. ];
  1791. }
  1792. /**
  1793. * @param string $url
  1794. * @param string $action
  1795. *
  1796. * @return FormValidator
  1797. */
  1798. public function return_form($url, $action)
  1799. {
  1800. $form = new FormValidator($this->type.'_field', 'post', $url);
  1801. $form->addElement('hidden', 'type', $this->type);
  1802. $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
  1803. $form->addElement('hidden', 'id', $id);
  1804. // Setting the form elements
  1805. $header = get_lang('Add');
  1806. $defaults = [];
  1807. if ($action === 'edit') {
  1808. $header = get_lang('Modify');
  1809. // Setting the defaults
  1810. $defaults = $this->get($id, false);
  1811. }
  1812. $form->addElement('header', $header);
  1813. if ($action === 'edit') {
  1814. $translateUrl = api_get_path(WEB_CODE_PATH).'extrafield/translate.php?'
  1815. .http_build_query(['extra_field' => $id]);
  1816. $translateButton = Display::toolbarButton(get_lang('TranslateThisTerm'), $translateUrl, 'language', 'link');
  1817. $form->addText(
  1818. 'display_text',
  1819. [get_lang('Name'), $translateButton]
  1820. );
  1821. } else {
  1822. $form->addElement('text', 'display_text', get_lang('Name'));
  1823. }
  1824. // Field type
  1825. $types = self::get_field_types();
  1826. $form->addElement(
  1827. 'select',
  1828. 'field_type',
  1829. get_lang('FieldType'),
  1830. $types,
  1831. ['id' => 'field_type']
  1832. );
  1833. $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
  1834. $form->addElement('text', 'variable', get_lang('FieldLabel'), ['class' => 'span5']);
  1835. $form->addElement(
  1836. 'text',
  1837. 'field_options',
  1838. get_lang('FieldPossibleValues'),
  1839. ['id' => 'field_options', 'class' => 'span6']
  1840. );
  1841. $fieldWithOptions = [
  1842. self::FIELD_TYPE_RADIO,
  1843. self::FIELD_TYPE_SELECT_MULTIPLE,
  1844. self::FIELD_TYPE_SELECT,
  1845. self::FIELD_TYPE_TAG,
  1846. self::FIELD_TYPE_DOUBLE_SELECT,
  1847. self::FIELD_TYPE_SELECT_WITH_TEXT_FIELD,
  1848. self::FIELD_TYPE_TRIPLE_SELECT,
  1849. ];
  1850. if ($action == 'edit') {
  1851. if (in_array($defaults['field_type'], $fieldWithOptions)) {
  1852. $url = Display::url(
  1853. get_lang('EditExtraFieldOptions'),
  1854. 'extra_field_options.php?type='.$this->type.'&field_id='.$id
  1855. );
  1856. $form->addElement('label', null, $url);
  1857. if ($defaults['field_type'] == self::FIELD_TYPE_SELECT) {
  1858. $urlWorkFlow = Display::url(
  1859. get_lang('EditExtraFieldWorkFlow'),
  1860. 'extra_field_workflow.php?type='.$this->type.'&field_id='.$id
  1861. );
  1862. $form->addElement('label', null, $urlWorkFlow);
  1863. }
  1864. $form->freeze('field_options');
  1865. }
  1866. }
  1867. $form->addElement(
  1868. 'text',
  1869. 'default_value',
  1870. get_lang('FieldDefaultValue'),
  1871. ['id' => 'default_value']
  1872. );
  1873. $group = [];
  1874. $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('Yes'), 1);
  1875. $group[] = $form->createElement('radio', 'visible_to_self', null, get_lang('No'), 0);
  1876. $form->addGroup($group, '', get_lang('VisibleToSelf'), null, false);
  1877. $group = [];
  1878. $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('Yes'), 1);
  1879. $group[] = $form->createElement('radio', 'visible_to_others', null, get_lang('No'), 0);
  1880. $form->addGroup($group, '', get_lang('VisibleToOthers'), null, false);
  1881. $group = [];
  1882. $group[] = $form->createElement('radio', 'changeable', null, get_lang('Yes'), 1);
  1883. $group[] = $form->createElement('radio', 'changeable', null, get_lang('No'), 0);
  1884. $form->addGroup($group, '', get_lang('FieldChangeability'), null, false);
  1885. $group = [];
  1886. $group[] = $form->createElement('radio', 'filter', null, get_lang('Yes'), 1);
  1887. $group[] = $form->createElement('radio', 'filter', null, get_lang('No'), 0);
  1888. $form->addGroup($group, '', get_lang('FieldFilter'), null, false);
  1889. /* Enable this when field_loggeable is introduced as a table field (2.0)
  1890. $group = array();
  1891. $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('Yes'), 1);
  1892. $group[] = $form->createElement('radio', 'field_loggeable', null, get_lang('No'), 0);
  1893. $form->addGroup($group, '', get_lang('FieldLoggeable'), '', false);
  1894. */
  1895. $form->addElement('text', 'field_order', get_lang('FieldOrder'));
  1896. if ($action == 'edit') {
  1897. $option = new ExtraFieldOption($this->type);
  1898. $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
  1899. $form->addButtonUpdate(get_lang('Modify'));
  1900. } else {
  1901. $defaults['visible_to_self'] = 0;
  1902. $defaults['visible_to_others'] = 0;
  1903. $defaults['changeable'] = 0;
  1904. $defaults['filter'] = 0;
  1905. $form->addButtonCreate(get_lang('Add'));
  1906. }
  1907. /*if (!empty($defaults['created_at'])) {
  1908. $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
  1909. }
  1910. if (!empty($defaults['updated_at'])) {
  1911. $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
  1912. }*/
  1913. $form->setDefaults($defaults);
  1914. // Setting the rules
  1915. $form->addRule('display_text', get_lang('ThisFieldIsRequired'), 'required');
  1916. $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
  1917. return $form;
  1918. }
  1919. /**
  1920. * @param $token
  1921. *
  1922. * @return string
  1923. */
  1924. public function getJqgridActionLinks($token)
  1925. {
  1926. //With this function we can add actions to the jgrid (edit, delete, etc)
  1927. $editIcon = Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL);
  1928. $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
  1929. $confirmMessage = addslashes(
  1930. api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES)
  1931. );
  1932. $editButton = <<<JAVASCRIPT
  1933. <a href="?action=edit&type={$this->type}&id=' + options.rowId + '" class="btn btn-link btn-xs">\
  1934. $editIcon\
  1935. </a>
  1936. JAVASCRIPT;
  1937. $deleteButton = <<<JAVASCRIPT
  1938. <a \
  1939. onclick="if (!confirm(\'$confirmMessage\')) {return false;}" \
  1940. href="?sec_token=$token&type={$this->type}&id=' + options.rowId + '&action=delete" \
  1941. class="btn btn-link btn-xs">\
  1942. $deleteIcon\
  1943. </a>
  1944. JAVASCRIPT;
  1945. return "function action_formatter(cellvalue, options, rowObject) {
  1946. return '$editButton $deleteButton';
  1947. }";
  1948. }
  1949. /**
  1950. * @param array $columns
  1951. * @param array $column_model
  1952. * @param array $extraFields
  1953. *
  1954. * @return array
  1955. */
  1956. public function getRules(&$columns, &$column_model, $extraFields = [], $checkExtraFieldExistence = false)
  1957. {
  1958. $fields = $this->get_all(
  1959. [
  1960. 'visible_to_self = ? AND filter = ?' => [1, 1],
  1961. ],
  1962. 'display_text'
  1963. );
  1964. $extraFieldOption = new ExtraFieldOption($this->type);
  1965. $rules = [];
  1966. if (!empty($fields)) {
  1967. foreach ($fields as $field) {
  1968. $search_options = [];
  1969. $type = 'text';
  1970. if (in_array($field['field_type'], [self::FIELD_TYPE_SELECT, self::FIELD_TYPE_DOUBLE_SELECT])) {
  1971. $type = 'select';
  1972. $search_options['sopt'] = ['eq', 'ne']; //equal not equal
  1973. } else {
  1974. $search_options['sopt'] = ['cn', 'nc']; //contains not contains
  1975. }
  1976. $search_options['searchhidden'] = 'true';
  1977. $search_options['defaultValue'] = isset($search_options['field_default_value'])
  1978. ? $search_options['field_default_value']
  1979. : null;
  1980. if ($field['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
  1981. // Add 2 selects
  1982. $options = $extraFieldOption->get_field_options_by_field($field['id']);
  1983. $options = self::extra_field_double_select_convert_array_to_ordered_array($options);
  1984. $first_options = [];
  1985. if (!empty($options)) {
  1986. foreach ($options as $option) {
  1987. foreach ($option as $sub_option) {
  1988. if ($sub_option['option_value'] == 0) {
  1989. $first_options[] = $sub_option['field_id'].'#'.$sub_option['id'].':'
  1990. .$sub_option['display_text'];
  1991. }
  1992. }
  1993. }
  1994. }
  1995. $search_options['value'] = implode(';', $first_options);
  1996. $search_options['dataInit'] = 'fill_second_select';
  1997. // First
  1998. $column_model[] = [
  1999. 'name' => 'extra_'.$field['variable'],
  2000. 'index' => 'extra_'.$field['variable'],
  2001. 'width' => '100',
  2002. 'hidden' => 'true',
  2003. 'search' => 'true',
  2004. 'stype' => 'select',
  2005. 'searchoptions' => $search_options,
  2006. ];
  2007. $columns[] = $field['display_text'].' (1)';
  2008. $rules[] = [
  2009. 'field' => 'extra_'.$field['variable'],
  2010. 'op' => 'cn',
  2011. ];
  2012. // Second
  2013. $search_options['value'] = $field['id'].':';
  2014. $search_options['dataInit'] = 'register_second_select';
  2015. $column_model[] = [
  2016. 'name' => 'extra_'.$field['variable'].'_second',
  2017. 'index' => 'extra_'.$field['variable'].'_second',
  2018. 'width' => '100',
  2019. 'hidden' => 'true',
  2020. 'search' => 'true',
  2021. 'stype' => 'select',
  2022. 'searchoptions' => $search_options,
  2023. ];
  2024. $columns[] = $field['display_text'].' (2)';
  2025. $rules[] = ['field' => 'extra_'.$field['variable'].'_second', 'op' => 'cn'];
  2026. continue;
  2027. } else {
  2028. $search_options['value'] = $extraFieldOption->getFieldOptionsToString(
  2029. $field['id'],
  2030. false,
  2031. 'display_text'
  2032. );
  2033. }
  2034. $column_model[] = [
  2035. 'name' => 'extra_'.$field['variable'],
  2036. 'index' => 'extra_'.$field['variable'],
  2037. 'width' => '100',
  2038. 'hidden' => 'true',
  2039. 'search' => 'true',
  2040. 'stype' => $type,
  2041. 'searchoptions' => $search_options,
  2042. ];
  2043. $columns[] = $field['display_text'];
  2044. $rules[] = [
  2045. 'field' => 'extra_'.$field['variable'],
  2046. 'op' => 'cn',
  2047. 'data' => '',
  2048. ];
  2049. }
  2050. }
  2051. return $rules;
  2052. }
  2053. /**
  2054. * @param array $options
  2055. *
  2056. * @return array
  2057. */
  2058. public function parseConditions($options)
  2059. {
  2060. $inject_extra_fields = null;
  2061. $extraFieldOption = new ExtraFieldOption($this->type);
  2062. $double_fields = [];
  2063. if (isset($options['extra'])) {
  2064. $extra_fields = $options['extra'];
  2065. if (!empty($extra_fields)) {
  2066. $counter = 1;
  2067. foreach ($extra_fields as &$extra) {
  2068. $extra_field_obj = new ExtraField($this->type);
  2069. $extra_field_info = $extra_field_obj->get($extra['id']);
  2070. $extra['extra_field_info'] = $extra_field_info;
  2071. if (isset($extra_field_info['field_type']) &&
  2072. in_array(
  2073. $extra_field_info['field_type'],
  2074. [
  2075. self::FIELD_TYPE_SELECT,
  2076. self::FIELD_TYPE_SELECT,
  2077. self::FIELD_TYPE_DOUBLE_SELECT,
  2078. ]
  2079. )
  2080. ) {
  2081. $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
  2082. } else {
  2083. $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
  2084. }
  2085. if (isset($extra_fields_info[$extra['id']])) {
  2086. $info = $extra_fields_info[$extra['id']];
  2087. } else {
  2088. $info = $this->get($extra['id']);
  2089. $extra_fields_info[$extra['id']] = $info;
  2090. }
  2091. if (isset($info['field_type']) && $info['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
  2092. $double_fields[$info['id']] = $info;
  2093. }
  2094. $counter++;
  2095. }
  2096. }
  2097. }
  2098. $options_by_double = [];
  2099. foreach ($double_fields as $double) {
  2100. $my_options = $extraFieldOption->get_field_options_by_field(
  2101. $double['id'],
  2102. true
  2103. );
  2104. $options_by_double['extra_'.$double['variable']] = $my_options;
  2105. }
  2106. $field_value_to_join = [];
  2107. //filter can be all/any = and/or
  2108. $inject_joins = null;
  2109. $inject_where = null;
  2110. $where = null;
  2111. if (!empty($options['where'])) {
  2112. if (!empty($options['extra'])) {
  2113. // Removing double 1=1
  2114. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  2115. // Always OR
  2116. $counter = 1;
  2117. foreach ($extra_fields as $extra_info) {
  2118. $extra_field_info = $extra_info['extra_field_info'];
  2119. $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
  2120. ON (s.".$this->primaryKey." = fv$counter.".$this->handler_id.") ";
  2121. // Add options
  2122. if (isset($extra_field_info['field_type']) &&
  2123. in_array(
  2124. $extra_field_info['field_type'],
  2125. [
  2126. self::FIELD_TYPE_SELECT,
  2127. self::FIELD_TYPE_SELECT,
  2128. self::FIELD_TYPE_DOUBLE_SELECT,
  2129. ]
  2130. )
  2131. ) {
  2132. $options['where'] = str_replace(
  2133. $extra_info['field'],
  2134. 'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fvo'.$counter.'.option_value',
  2135. $options['where']
  2136. );
  2137. $inject_joins .= "
  2138. INNER JOIN $this->table_field_options fvo$counter
  2139. ON (
  2140. fv$counter.field_id = fvo$counter.field_id AND
  2141. fv$counter.value = fvo$counter.option_value
  2142. )
  2143. ";
  2144. } else {
  2145. if (isset($extra_field_info['field_type']) &&
  2146. $extra_field_info['field_type'] == self::FIELD_TYPE_TAG
  2147. ) {
  2148. $options['where'] = str_replace(
  2149. $extra_info['field'],
  2150. 'tag'.$counter.'.tag ',
  2151. $options['where']
  2152. );
  2153. $inject_joins .= "
  2154. INNER JOIN $this->table_field_rel_tag tag_rel$counter
  2155. ON (
  2156. tag_rel$counter.field_id = ".$extra_info['id']." AND
  2157. tag_rel$counter.item_id = s.".$this->primaryKey."
  2158. )
  2159. INNER JOIN $this->table_field_tag tag$counter
  2160. ON (tag$counter.id = tag_rel$counter.tag_id)
  2161. ";
  2162. } else {
  2163. //text, textarea, etc
  2164. $options['where'] = str_replace(
  2165. $extra_info['field'],
  2166. 'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
  2167. $options['where']
  2168. );
  2169. }
  2170. }
  2171. $field_value_to_join[] = " fv$counter.$this->handler_id ";
  2172. $counter++;
  2173. }
  2174. if (!empty($field_value_to_join)) {
  2175. //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
  2176. }
  2177. }
  2178. $where .= ' AND '.$options['where'];
  2179. }
  2180. $order = null;
  2181. if (!empty($options['order'])) {
  2182. $order = " ORDER BY ".$options['order'];
  2183. }
  2184. $limit = null;
  2185. if (!empty($options['limit'])) {
  2186. $limit = " LIMIT ".$options['limit'];
  2187. }
  2188. return [
  2189. 'order' => $order,
  2190. 'limit' => $limit,
  2191. 'where' => $where,
  2192. 'inject_where' => $inject_where,
  2193. 'inject_joins' => $inject_joins,
  2194. 'field_value_to_join' => $field_value_to_join,
  2195. 'inject_extra_fields' => $inject_extra_fields,
  2196. ];
  2197. }
  2198. //@todo move this in the display_class or somewhere else
  2199. /**
  2200. * @param $col
  2201. * @param $oper
  2202. * @param $val
  2203. *
  2204. * @return string
  2205. */
  2206. public function get_where_clause($col, $oper, $val)
  2207. {
  2208. if (empty($col)) {
  2209. return '';
  2210. }
  2211. if ($oper == 'bw' || $oper == 'bn') {
  2212. $val .= '%';
  2213. }
  2214. if ($oper == 'ew' || $oper == 'en') {
  2215. $val = '%'.$val;
  2216. }
  2217. if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
  2218. if (is_array($val)) {
  2219. $result = '"%'.implode(';', $val).'%"';
  2220. foreach ($val as $item) {
  2221. $item = trim($item);
  2222. $result .= ' OR '.$col.' LIKE "%'.$item.'%"';
  2223. }
  2224. $val = $result;
  2225. return " $col {$this->ops[$oper]} $val ";
  2226. } else {
  2227. if (is_string($val)) {
  2228. $val = '%'.$val.'%';
  2229. } else {
  2230. $val = '';
  2231. }
  2232. }
  2233. }
  2234. $val = \Database::escape_string($val);
  2235. return " $col {$this->ops[$oper]} '$val' ";
  2236. }
  2237. /**
  2238. * @param $filters
  2239. * @param string $stringToSearch
  2240. *
  2241. * @return array
  2242. */
  2243. public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
  2244. {
  2245. $extra_fields = [];
  2246. // Getting double select if exists
  2247. $double_select = [];
  2248. foreach ($filters->rules as $rule) {
  2249. if (empty($rule)) {
  2250. continue;
  2251. }
  2252. if (strpos($rule->field, '_second') === false) {
  2253. } else {
  2254. $my_field = str_replace('_second', '', $rule->field);
  2255. $double_select[$my_field] = $rule->data;
  2256. }
  2257. }
  2258. $condition_array = [];
  2259. foreach ($filters->rules as $rule) {
  2260. if (empty($rule)) {
  2261. continue;
  2262. }
  2263. if (strpos($rule->field, $stringToSearch) === false) {
  2264. // normal fields
  2265. $field = $rule->field;
  2266. if (isset($rule->data) && is_string($rule->data) && $rule->data != -1) {
  2267. $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
  2268. }
  2269. } else {
  2270. // Extra fields
  2271. if (strpos($rule->field, '_second') === false) {
  2272. //No _second
  2273. $original_field = str_replace($stringToSearch, '', $rule->field);
  2274. $field_option = $this->get_handler_field_info_by_field_variable($original_field);
  2275. if ($field_option['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
  2276. if (isset($double_select[$rule->field])) {
  2277. $data = explode('#', $rule->data);
  2278. $rule->data = $data[1].'::'.$double_select[$rule->field];
  2279. } else {
  2280. // only was sent 1 select
  2281. if (is_string($rule->data)) {
  2282. $data = explode('#', $rule->data);
  2283. $rule->data = $data[1];
  2284. }
  2285. }
  2286. if (!isset($rule->data)) {
  2287. $condition_array[] = ' ('
  2288. .$this->get_where_clause($rule->field, $rule->op, $rule->data)
  2289. .') ';
  2290. $extra_fields[] = ['field' => $rule->field, 'id' => $field_option['id']];
  2291. }
  2292. } else {
  2293. if (isset($rule->data)) {
  2294. if (isset($rule->data) && is_int($rule->data) && $rule->data == -1) {
  2295. continue;
  2296. }
  2297. $condition_array[] = ' ('
  2298. .$this->get_where_clause($rule->field, $rule->op, $rule->data)
  2299. .') ';
  2300. $extra_fields[] = [
  2301. 'field' => $rule->field,
  2302. 'id' => $field_option['id'],
  2303. 'data' => $rule->data,
  2304. ];
  2305. }
  2306. }
  2307. } else {
  2308. $my_field = str_replace('_second', '', $rule->field);
  2309. $original_field = str_replace($stringToSearch, '', $my_field);
  2310. $field_option = $this->get_handler_field_info_by_field_variable($original_field);
  2311. $extra_fields[] = [
  2312. 'field' => $rule->field,
  2313. 'id' => $field_option['id'],
  2314. ];
  2315. }
  2316. }
  2317. }
  2318. return [
  2319. 'extra_fields' => $extra_fields,
  2320. 'condition_array' => $condition_array,
  2321. ];
  2322. }
  2323. /**
  2324. * Get the extra fields and their formatted values.
  2325. *
  2326. * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
  2327. *
  2328. * @return array The extra fields data
  2329. */
  2330. public function getDataAndFormattedValues($itemId)
  2331. {
  2332. $valuesData = [];
  2333. $fields = $this->get_all();
  2334. $em = Database::getManager();
  2335. foreach ($fields as $field) {
  2336. if ($field['visible_to_self'] != '1') {
  2337. continue;
  2338. }
  2339. $fieldValue = new ExtraFieldValue($this->type);
  2340. $valueData = $fieldValue->get_values_by_handler_and_field_id(
  2341. $itemId,
  2342. $field['id'],
  2343. true
  2344. );
  2345. if ($field['field_type'] == ExtraField::FIELD_TYPE_TAG) {
  2346. $tags = $em
  2347. ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  2348. ->findBy(
  2349. [
  2350. 'fieldId' => $field['id'],
  2351. 'itemId' => $itemId,
  2352. ]
  2353. );
  2354. if ($tags) {
  2355. /** @var \Chamilo\CoreBundle\Entity\ExtraFieldRelTag $tag */
  2356. $data = [];
  2357. foreach ($tags as $extraFieldTag) {
  2358. /** @var \Chamilo\CoreBundle\Entity\Tag $tag */
  2359. $tag = $em->find('ChamiloCoreBundle:Tag', $extraFieldTag->getTagId());
  2360. /*$data[] = [
  2361. 'id' => $extraFieldTag->getTagId(),
  2362. 'value' => $tag->getTag()
  2363. ];*/
  2364. $data[] = $tag->getTag();
  2365. }
  2366. $valueData = implode(',', $data);
  2367. }
  2368. }
  2369. if (!$valueData) {
  2370. continue;
  2371. }
  2372. $displayedValue = get_lang('None');
  2373. switch ($field['field_type']) {
  2374. case self::FIELD_TYPE_CHECKBOX:
  2375. if ($valueData !== false && $valueData['value'] == '1') {
  2376. $displayedValue = get_lang('Yes');
  2377. } else {
  2378. $displayedValue = get_lang('No');
  2379. }
  2380. break;
  2381. case self::FIELD_TYPE_DATE:
  2382. if ($valueData !== false && !empty($valueData['value'])) {
  2383. $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
  2384. }
  2385. break;
  2386. case self::FIELD_TYPE_TAG:
  2387. if (!empty($valueData)) {
  2388. $displayedValue = $valueData;
  2389. }
  2390. break;
  2391. case self::FIELD_TYPE_FILE_IMAGE:
  2392. if ($valueData === false || empty($valueData['value'])) {
  2393. break;
  2394. }
  2395. if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
  2396. break;
  2397. }
  2398. $image = Display::img(
  2399. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2400. $field['display_text'],
  2401. ['width' => '300']
  2402. );
  2403. $displayedValue = Display::url(
  2404. $image,
  2405. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2406. ['target' => '_blank']
  2407. );
  2408. break;
  2409. case self::FIELD_TYPE_FILE:
  2410. if ($valueData === false || empty($valueData['value'])) {
  2411. break;
  2412. }
  2413. if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
  2414. break;
  2415. }
  2416. $displayedValue = Display::url(
  2417. get_lang('Download'),
  2418. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2419. [
  2420. 'title' => $field['display_text'],
  2421. 'target' => '_blank',
  2422. ]
  2423. );
  2424. break;
  2425. default:
  2426. $displayedValue = $valueData['value'];
  2427. break;
  2428. }
  2429. $valuesData[] = [
  2430. 'text' => $field['display_text'],
  2431. 'value' => $displayedValue,
  2432. ];
  2433. }
  2434. return $valuesData;
  2435. }
  2436. /**
  2437. * Gets an element.
  2438. *
  2439. * @param int $id
  2440. * @param bool $translateDisplayText Optional
  2441. *
  2442. * @return array
  2443. */
  2444. public function get($id, $translateDisplayText = true)
  2445. {
  2446. $info = parent::get($id);
  2447. if ($translateDisplayText) {
  2448. $info['display_text'] = self::translateDisplayName($info['variable'], $info['display_text']);
  2449. }
  2450. return $info;
  2451. }
  2452. /**
  2453. * Translate the display text for a extra field.
  2454. *
  2455. * @param string $variable
  2456. * @param string $defaultDisplayText
  2457. *
  2458. * @return string
  2459. */
  2460. public static function translateDisplayName($variable, $defaultDisplayText)
  2461. {
  2462. $camelCase = api_underscore_to_camel_case($variable);
  2463. return isset($GLOBALS[$camelCase]) ? $GLOBALS[$camelCase] : $defaultDisplayText;
  2464. }
  2465. /**
  2466. * @param int $fieldId
  2467. * @param string $tag
  2468. *
  2469. * @return array
  2470. */
  2471. public function getAllUserPerTag($fieldId, $tag)
  2472. {
  2473. $tagRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2474. $tag = Database::escape_string($tag);
  2475. $fieldId = (int) $fieldId;
  2476. $sql = "SELECT user_id
  2477. FROM {$this->table_field_tag} f INNER JOIN $tagRelUserTable ft
  2478. ON tag_id = f.id
  2479. WHERE tag = '$tag' AND f.field_id = $fieldId;
  2480. ";
  2481. $result = Database::query($sql);
  2482. return Database::store_result($result, 'ASSOC');
  2483. }
  2484. /**
  2485. * @param int $fieldId
  2486. * @param int $tagId
  2487. *
  2488. * @return array
  2489. */
  2490. public function getAllSkillPerTag($fieldId, $tagId)
  2491. {
  2492. $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
  2493. $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
  2494. $fieldId = intval($fieldId);
  2495. $tagId = intval($tagId);
  2496. $sql = "SELECT s.id
  2497. FROM $skillTable s INNER JOIN $tagRelExtraTable t
  2498. ON t.item_id = s.id
  2499. WHERE tag_id = $tagId AND t.field_id = $fieldId;
  2500. ";
  2501. $result = Database::query($sql);
  2502. $result = Database::store_result($result, 'ASSOC');
  2503. $skillList = [];
  2504. foreach ($result as $index => $value) {
  2505. $skillList[$value['id']] = $value['id'];
  2506. }
  2507. return $skillList;
  2508. }
  2509. /**
  2510. * @param string $from
  2511. * @param string $search
  2512. * @param array $options
  2513. *
  2514. * @return array
  2515. */
  2516. public function searchOptionsFromTags($from, $search, $options)
  2517. {
  2518. $extraFieldInfo = $this->get_handler_field_info_by_field_variable(
  2519. str_replace('extra_', '', $from)
  2520. );
  2521. $extraFieldInfoTag = $this->get_handler_field_info_by_field_variable(
  2522. str_replace('extra_', '', $search)
  2523. );
  2524. if (empty($extraFieldInfo) || empty($extraFieldInfoTag)) {
  2525. return [];
  2526. }
  2527. $id = $extraFieldInfo['id'];
  2528. $tagId = $extraFieldInfoTag['id'];
  2529. $table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2530. $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
  2531. $tagTable = Database::get_main_table(TABLE_MAIN_TAG);
  2532. $optionsTable = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  2533. $sql = "SELECT DISTINCT t.*, v.value, o.display_text
  2534. FROM $tagRelExtraTable te
  2535. INNER JOIN $tagTable t
  2536. ON (t.id = te.tag_id AND te.field_id = t.field_id AND te.field_id = $tagId)
  2537. INNER JOIN $table v
  2538. ON (te.item_id = v.item_id AND v.field_id = $id)
  2539. INNER JOIN $optionsTable o
  2540. ON (o.option_value = v.value)
  2541. WHERE v.value IN ('".implode("','", $options)."')
  2542. ORDER BY o.option_order, t.tag
  2543. ";
  2544. $result = Database::query($sql);
  2545. $result = Database::store_result($result);
  2546. return $result;
  2547. }
  2548. /**
  2549. * @param string $variable
  2550. * @param string $dataValue
  2551. *
  2552. * @return string
  2553. */
  2554. public static function getLocalizationJavascript($variable, $dataValue)
  2555. {
  2556. $dataValue = addslashes($dataValue);
  2557. $html = "<script>
  2558. $(function() {
  2559. if (typeof google === 'object') {
  2560. var address = '$dataValue';
  2561. initializeGeo{$variable}(address, false);
  2562. $('#geolocalization_extra_{$variable}').on('click', function() {
  2563. var address = $('#{$variable}').val();
  2564. initializeGeo{$variable}(address, false);
  2565. return false;
  2566. });
  2567. $('#myLocation_extra_{$variable}').on('click', function() {
  2568. myLocation{$variable}();
  2569. return false;
  2570. });
  2571. // When clicking enter
  2572. $('#{$variable}').keypress(function(event) {
  2573. if (event.which == 13) {
  2574. $('#geolocalization_extra_{$variable}').click();
  2575. return false;
  2576. }
  2577. });
  2578. // On focus out update city
  2579. $('#{$variable}').focusout(function() {
  2580. $('#geolocalization_extra_{$variable}').click();
  2581. return false;
  2582. });
  2583. return;
  2584. }
  2585. $('#map_extra_{$variable}')
  2586. .html('<div class=\"alert alert-info\">"
  2587. .addslashes(get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap'))
  2588. ."</div>');
  2589. });
  2590. function myLocation{$variable}()
  2591. {
  2592. if (navigator.geolocation) {
  2593. var geoPosition = function(position) {
  2594. var lat = position.coords.latitude;
  2595. var lng = position.coords.longitude;
  2596. var latLng = new google.maps.LatLng(lat, lng);
  2597. initializeGeo{$variable}(false, latLng);
  2598. };
  2599. var geoError = function(error) {
  2600. alert('Geocode ".get_lang('Error').": ' + error);
  2601. };
  2602. var geoOptions = {
  2603. enableHighAccuracy: true
  2604. };
  2605. navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
  2606. }
  2607. }
  2608. function initializeGeo{$variable}(address, latLng)
  2609. {
  2610. var geocoder = new google.maps.Geocoder();
  2611. var latlng = new google.maps.LatLng(-34.397, 150.644);
  2612. var myOptions = {
  2613. zoom: 15,
  2614. center: latlng,
  2615. mapTypeControl: true,
  2616. mapTypeControlOptions: {
  2617. style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  2618. },
  2619. navigationControl: true,
  2620. mapTypeId: google.maps.MapTypeId.ROADMAP
  2621. };
  2622. map_{$variable} = new google.maps.Map(
  2623. document.getElementById('map_extra_{$variable}'),
  2624. myOptions
  2625. );
  2626. var parameter = address ? {'address': address} : latLng ? {'latLng': latLng} : false;
  2627. if (geocoder && parameter) {
  2628. geocoder.geocode(parameter, function(results, status) {
  2629. if (status == google.maps.GeocoderStatus.OK) {
  2630. if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  2631. map_{$variable}.setCenter(results[0].geometry.location);
  2632. // get city and country
  2633. var defaultAddress = results[0].formatted_address;
  2634. var city = '';
  2635. var country = '';
  2636. for (var i=0; i<results[0].address_components.length; i++) {
  2637. if (results[0].address_components[i].types[0] == \"locality\") {
  2638. //this is the object you are looking for City
  2639. city = results[0].address_components[i];
  2640. }
  2641. /*if (results[j].address_components[i].types[0] == \"administrative_area_level_1\") {
  2642. //this is the object you are looking for State
  2643. region = results[0].address_components[i];
  2644. }*/
  2645. if (results[0].address_components[i].types[0] == \"country\") {
  2646. //this is the object you are looking for
  2647. country = results[0].address_components[i];
  2648. }
  2649. }
  2650. if (city && city.long_name && country && country.long_name) {
  2651. defaultAddress = city.long_name + ', ' + country.long_name;
  2652. }
  2653. $('#{$variable}').val(defaultAddress);
  2654. $('#{$variable}_coordinates').val(
  2655. results[0].geometry.location.lat()+','+results[0].geometry.location.lng()
  2656. );
  2657. var infowindow = new google.maps.InfoWindow({
  2658. content: '<b>' + $('#extra_{$variable}').val() + '</b>',
  2659. size: new google.maps.Size(150, 50)
  2660. });
  2661. var marker = new google.maps.Marker({
  2662. position: results[0].geometry.location,
  2663. map: map_{$variable},
  2664. title: $('#extra_{$variable}').val()
  2665. });
  2666. google.maps.event.addListener(marker, 'click', function() {
  2667. infowindow.open(map_{$variable}, marker);
  2668. });
  2669. } else {
  2670. alert('".get_lang('NotFound')."');
  2671. }
  2672. } else {
  2673. alert('Geocode ".get_lang('Error').": ".get_lang("AddressField")." ".get_lang('NotFound')."');
  2674. }
  2675. });
  2676. }
  2677. }
  2678. </script>";
  2679. return $html;
  2680. }
  2681. /**
  2682. * @param string $variable
  2683. * @param string $text
  2684. *
  2685. * @return string
  2686. */
  2687. public static function getLocalizationInput($variable, $text)
  2688. {
  2689. $html = '
  2690. <div class="form-group">
  2691. <label for="geolocalization_extra_'.$variable.'"
  2692. class="col-sm-2 control-label"></label>
  2693. <div class="col-sm-8">
  2694. <button class="btn btn-default"
  2695. id="geolocalization_extra_'.$variable.'"
  2696. name="geolocalization_extra_'.$variable.'"
  2697. type="submit">
  2698. <em class="fa fa-map-marker"></em> '.get_lang('SearchGeolocalization').'
  2699. </button>
  2700. <button class="btn btn-default" id="myLocation_extra_'.$variable.'"
  2701. name="myLocation_extra_'.$variable.'"
  2702. type="submit">
  2703. <em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'
  2704. </button>
  2705. </div>
  2706. </div>
  2707. <div class="form-group">
  2708. <label for="map_extra_'.$variable.'" class="col-sm-2 control-label">
  2709. '.$text.' - '.get_lang('Map').'
  2710. </label>
  2711. <div class="col-sm-8">
  2712. <div name="map_extra_'.$variable.'"
  2713. id="map_extra_'.$variable.'" style="width:100%; height:300px;">
  2714. </div>
  2715. </div>
  2716. </div>
  2717. ';
  2718. return $html;
  2719. }
  2720. /**
  2721. * @param array $options
  2722. * @param int $parentId
  2723. *
  2724. * @return array
  2725. */
  2726. private static function getOptionsFromTripleSelect(array $options, $parentId)
  2727. {
  2728. return array_filter($options, function ($option) use ($parentId) {
  2729. return $option['option_value'] == $parentId;
  2730. });
  2731. }
  2732. /**
  2733. * @param \FormValidator $form
  2734. * @param array $fieldDetails
  2735. * @param int $defaultValueId
  2736. * @param bool $freezeElement
  2737. */
  2738. private function addSelectElement(FormValidator $form, array $fieldDetails, $defaultValueId, $freezeElement = false)
  2739. {
  2740. $get_lang_variables = false;
  2741. if (in_array(
  2742. $fieldDetails['variable'],
  2743. ['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
  2744. )) {
  2745. $get_lang_variables = true;
  2746. }
  2747. // Get extra field workflow
  2748. $addOptions = [];
  2749. $optionsExists = false;
  2750. $options = [];
  2751. $optionList = [];
  2752. if (!empty($fieldDetails['options'])) {
  2753. foreach ($fieldDetails['options'] as $option_details) {
  2754. $optionList[$option_details['id']] = $option_details;
  2755. if ($get_lang_variables) {
  2756. $options[$option_details['option_value']] = $option_details['display_text'];
  2757. } else {
  2758. if ($optionsExists) {
  2759. // Adding always the default value
  2760. if ($option_details['id'] == $defaultValueId) {
  2761. $options[$option_details['option_value']] = $option_details['display_text'];
  2762. } else {
  2763. if (isset($addOptions) && !empty($addOptions)) {
  2764. // Parsing filters
  2765. if (in_array($option_details['id'], $addOptions)) {
  2766. $options[$option_details['option_value']] = $option_details['display_text'];
  2767. }
  2768. }
  2769. }
  2770. } else {
  2771. // Normal behaviour
  2772. $options[$option_details['option_value']] = $option_details['display_text'];
  2773. }
  2774. }
  2775. }
  2776. // Setting priority message
  2777. if (isset($optionList[$defaultValueId])
  2778. && isset($optionList[$defaultValueId]['priority'])
  2779. ) {
  2780. if (!empty($optionList[$defaultValueId]['priority'])) {
  2781. $priorityId = $optionList[$defaultValueId]['priority'];
  2782. $option = new ExtraFieldOption($this->type);
  2783. $messageType = $option->getPriorityMessageType($priorityId);
  2784. $form->addElement(
  2785. 'label',
  2786. null,
  2787. Display::return_message(
  2788. $optionList[$defaultValueId]['priority_message'],
  2789. $messageType
  2790. )
  2791. );
  2792. }
  2793. }
  2794. }
  2795. /** @var \HTML_QuickForm_select $slct */
  2796. $slct = $form->addElement(
  2797. 'select',
  2798. 'extra_'.$fieldDetails['variable'],
  2799. $fieldDetails['display_text'],
  2800. [],
  2801. ['id' => 'extra_'.$fieldDetails['variable']]
  2802. );
  2803. if (empty($defaultValueId)) {
  2804. $slct->addOption(get_lang('SelectAnOption'), '');
  2805. }
  2806. foreach ($options as $value => $text) {
  2807. if (empty($value)) {
  2808. $slct->addOption($text, $value);
  2809. continue;
  2810. }
  2811. $valueParts = explode('#', $text);
  2812. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  2813. $slct->addOption(implode('', $valueParts), $value, ['data-value' => $dataValue]);
  2814. }
  2815. /* Enable this when field_loggeable is introduced as a table field (2.0)
  2816. if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
  2817. $form->addElement(
  2818. 'textarea',
  2819. 'extra_' . $field_details['variable'] . '_comment',
  2820. $field_details['display_text'] . ' ' . get_lang('Comment')
  2821. );
  2822. $extraFieldValue = new ExtraFieldValue($this->type);
  2823. $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
  2824. $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
  2825. $newEntity = $repo->findOneBy(
  2826. array(
  2827. $this->handlerEntityId => $itemId,
  2828. 'fieldId' => $field_details['id']
  2829. )
  2830. );
  2831. // @todo move this in a function inside the class
  2832. if ($newEntity) {
  2833. $logs = $repoLog->getLogEntries($newEntity);
  2834. if (!empty($logs)) {
  2835. $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />';
  2836. $table = new HTML_Table(array('class' => 'data_table'));
  2837. $table->setHeaderContents(0, 0, get_lang('Value'));
  2838. $table->setHeaderContents(0, 1, get_lang('Comment'));
  2839. $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
  2840. $table->setHeaderContents(0, 3, get_lang('Username'));
  2841. $row = 1;
  2842. foreach ($logs as $log) {
  2843. $column = 0;
  2844. $data = $log->getData();
  2845. $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
  2846. $comment = isset($data['comment']) ? $data['comment'] : null;
  2847. $table->setCellContents($row, $column, $fieldValue);
  2848. $column++;
  2849. $table->setCellContents($row, $column, $comment);
  2850. $column++;
  2851. $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
  2852. $column++;
  2853. $table->setCellContents($row, $column, $log->getUsername());
  2854. $row++;
  2855. }
  2856. $form->addElement('label', null, $html.$table->toHtml());
  2857. }
  2858. }
  2859. }
  2860. */
  2861. if ($freezeElement) {
  2862. $form->freeze('extra_'.$fieldDetails['variable']);
  2863. }
  2864. }
  2865. /**
  2866. * @param \FormValidator $form
  2867. * @param array $fieldDetails
  2868. * @param array $extraData
  2869. * @param bool $freezeElement
  2870. *
  2871. * @return string JavaScript code
  2872. */
  2873. private function addDoubleSelectElement(FormValidator $form, $fieldDetails, $extraData, $freezeElement = false)
  2874. {
  2875. $firstSelectId = 'first_extra_'.$fieldDetails['variable'];
  2876. $secondSelectId = 'second_extra_'.$fieldDetails['variable'];
  2877. $jqueryReadyContent = "
  2878. $('#$firstSelectId').on('change', function() {
  2879. var id = $(this).val();
  2880. if (!id) {
  2881. $('#$secondSelectId').empty().selectpicker('refresh');
  2882. return;
  2883. }
  2884. $.getJSON(_p.web_ajax + 'extra_field.ajax.php?1=1&a=get_second_select_options', {
  2885. 'type': '{$this->type}',
  2886. 'field_id': {$fieldDetails['id']},
  2887. 'option_value_id': id
  2888. })
  2889. .done(function(data) {
  2890. $('#$secondSelectId').empty();
  2891. $.each(data, function(index, value) {
  2892. $('#second_extra_{$fieldDetails['variable']}').append(
  2893. $('<option>', {value: index, text: value})
  2894. );
  2895. });
  2896. $('#$secondSelectId').selectpicker('refresh');
  2897. });
  2898. });
  2899. ";
  2900. $firstId = null;
  2901. if (!empty($extraData)) {
  2902. if (isset($extraData['extra_'.$fieldDetails['variable']])) {
  2903. $firstId = $extraData['extra_'.$fieldDetails['variable']]['extra_'.$fieldDetails['variable']];
  2904. }
  2905. }
  2906. $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
  2907. $values = ['' => get_lang('Select')];
  2908. $second_values = [];
  2909. if (!empty($options)) {
  2910. foreach ($options as $option) {
  2911. foreach ($option as $sub_option) {
  2912. if ($sub_option['option_value'] == '0') {
  2913. $values[$sub_option['id']] = $sub_option['display_text'];
  2914. continue;
  2915. }
  2916. if ($firstId === $sub_option['option_value']) {
  2917. $second_values[$sub_option['id']] = $sub_option['display_text'];
  2918. }
  2919. }
  2920. }
  2921. }
  2922. $form
  2923. ->defaultRenderer()
  2924. ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
  2925. $group = [];
  2926. $group[] = $form->createElement(
  2927. 'select',
  2928. 'extra_'.$fieldDetails['variable'],
  2929. null,
  2930. $values,
  2931. ['id' => $firstSelectId]
  2932. );
  2933. $group[] = $form->createElement(
  2934. 'select',
  2935. 'extra_'.$fieldDetails['variable'].'_second',
  2936. null,
  2937. $second_values,
  2938. ['id' => $secondSelectId]
  2939. );
  2940. $form->addGroup(
  2941. $group,
  2942. 'extra_'.$fieldDetails['variable'],
  2943. $fieldDetails['display_text']
  2944. );
  2945. if ($freezeElement) {
  2946. $form->freeze('extra_'.$fieldDetails['variable']);
  2947. }
  2948. return $jqueryReadyContent;
  2949. }
  2950. /**
  2951. * @param \FormValidator $form
  2952. * @param array $fieldDetails
  2953. * @param bool $freezeElement Optional
  2954. *
  2955. * @return string JavaScript code
  2956. */
  2957. private function addSelectWithTextFieldElement(
  2958. FormValidator $form,
  2959. array $fieldDetails,
  2960. $freezeElement = false
  2961. ) {
  2962. $firstSelectId = 'slct_extra_'.$fieldDetails['variable'];
  2963. $txtSelectId = 'txt_extra_'.$fieldDetails['variable'];
  2964. $jqueryReadyContent = "
  2965. $('#$firstSelectId').on('change', function() {
  2966. var id = $(this).val();
  2967. if (!id) {
  2968. $('#$txtSelectId').val('');
  2969. }
  2970. });
  2971. ";
  2972. $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
  2973. $values = ['' => get_lang('Select')];
  2974. if (!empty($options)) {
  2975. foreach ($options as $option) {
  2976. foreach ($option as $sub_option) {
  2977. if ($sub_option['option_value'] != '0') {
  2978. continue;
  2979. }
  2980. $values[$sub_option['id']] = $sub_option['display_text'];
  2981. }
  2982. }
  2983. }
  2984. $form
  2985. ->defaultRenderer()
  2986. ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
  2987. $group = [];
  2988. $group[] = $form->createElement(
  2989. 'select',
  2990. 'extra_'.$fieldDetails['variable'],
  2991. null,
  2992. $values,
  2993. ['id' => $firstSelectId]
  2994. );
  2995. $group[] = $form->createElement(
  2996. 'text',
  2997. 'extra_'.$fieldDetails['variable'].'_second',
  2998. null,
  2999. ['id' => $txtSelectId]
  3000. );
  3001. $form->addGroup(
  3002. $group,
  3003. 'extra_'.$fieldDetails['variable'],
  3004. $fieldDetails['display_text']
  3005. );
  3006. if ($freezeElement) {
  3007. $form->freeze('extra_'.$fieldDetails['variable']);
  3008. }
  3009. return $jqueryReadyContent;
  3010. }
  3011. /**
  3012. * @param \FormValidator $form
  3013. * @param array $fieldDetails
  3014. * @param array $extraData
  3015. * @param bool $freezeElement
  3016. *
  3017. * @return string
  3018. */
  3019. private function addTripleSelectElement(
  3020. FormValidator $form,
  3021. array $fieldDetails,
  3022. array $extraData,
  3023. $freezeElement
  3024. ) {
  3025. $variable = $fieldDetails['variable'];
  3026. $id = $fieldDetails['id'];
  3027. $slctFirstId = "first_extra$variable";
  3028. $slctSecondId = "second_extra$variable";
  3029. $slctThirdId = "third_extra$variable";
  3030. $langSelect = get_lang('Select');
  3031. $js = "
  3032. (function () {
  3033. var slctFirst = $('#$slctFirstId'),
  3034. slctSecond = $('#$slctSecondId'),
  3035. slctThird = $('#$slctThirdId');
  3036. slctFirst.on('change', function () {
  3037. slctSecond.empty().selectpicker('refresh');
  3038. slctThird.empty().selectpicker('refresh');
  3039. var level = $(this).val();
  3040. if (!level) {
  3041. return;
  3042. }
  3043. $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
  3044. 'a': 'get_second_select_options',
  3045. 'type': '$this->type',
  3046. 'field_id': $id,
  3047. 'option_value_id': level
  3048. })
  3049. .done(function (data) {
  3050. slctSecond.append(
  3051. $('<option>', {value: '', text: '$langSelect'})
  3052. );
  3053. $.each(data, function (index, value) {
  3054. var valueParts = value.split('#'),
  3055. dataValue = valueParts.length > 1 ? valueParts.shift() : '';
  3056. slctSecond.append(
  3057. $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
  3058. );
  3059. });
  3060. slctSecond.selectpicker('refresh');
  3061. });
  3062. });
  3063. slctSecond.on('change', function () {
  3064. slctThird.empty().selectpicker('refresh');
  3065. var level = $(this).val();
  3066. if (!level) {
  3067. return;
  3068. }
  3069. $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
  3070. 'a': 'get_second_select_options',
  3071. 'type': '$this->type',
  3072. 'field_id': $id,
  3073. 'option_value_id': level
  3074. })
  3075. .done(function (data) {
  3076. slctThird.append(
  3077. $('<option>', {value: '', text: '$langSelect'})
  3078. );
  3079. $.each(data, function (index, value) {
  3080. var valueParts = value.split('#'),
  3081. dataValue = valueParts.length > 1 ? valueParts.shift() : '';
  3082. slctThird.append(
  3083. $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
  3084. );
  3085. });
  3086. slctThird.selectpicker('refresh');
  3087. });
  3088. });
  3089. })();
  3090. ";
  3091. $firstId = isset($extraData["extra_$variable"]["extra_$variable"])
  3092. ? $extraData["extra_$variable"]["extra_$variable"]
  3093. : '';
  3094. $secondId = isset($extraData["extra_$variable"]["extra_{$variable}_second"])
  3095. ? $extraData["extra_$variable"]["extra_{$variable}_second"]
  3096. : '';
  3097. $options = $this->tripleSelectConvertArrayToOrderedArray($fieldDetails['options']);
  3098. $values1 = ['' => $langSelect];
  3099. $values2 = ['' => $langSelect];
  3100. $values3 = ['' => $langSelect];
  3101. $level1 = $this->getOptionsFromTripleSelect($options['level1'], 0);
  3102. $level2 = $this->getOptionsFromTripleSelect($options['level2'], $firstId);
  3103. $level3 = $this->getOptionsFromTripleSelect($options['level3'], $secondId);
  3104. /** @var \HTML_QuickForm_select $slctFirst */
  3105. $slctFirst = $form->createElement('select', "extra_$variable", null, $values1, ['id' => $slctFirstId]);
  3106. /** @var \HTML_QuickForm_select $slctFirst */
  3107. $slctSecond = $form->createElement('select', "extra_{$variable}_second", null, $values2, ['id' => $slctSecondId]);
  3108. /** @var \HTML_QuickForm_select $slctFirst */
  3109. $slctThird = $form->createElement('select', "extra_{$variable}_third", null, $values3, ['id' => $slctThirdId]);
  3110. foreach ($level1 as $item1) {
  3111. $valueParts = explode('#', $item1['display_text']);
  3112. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3113. $slctFirst->addOption(implode('', $valueParts), $item1['id'], ['data-value' => $dataValue]);
  3114. }
  3115. foreach ($level2 as $item2) {
  3116. $valueParts = explode('#', $item2['display_text']);
  3117. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3118. $slctSecond->addOption(implode('', $valueParts), $item2['id'], ['data-value' => $dataValue]);
  3119. }
  3120. foreach ($level3 as $item3) {
  3121. $valueParts = explode('#', $item3['display_text']);
  3122. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3123. $slctThird->addOption(implode('', $valueParts), $item3['id'], ['data-value' => $dataValue]);
  3124. }
  3125. $form
  3126. ->defaultRenderer()
  3127. ->setGroupElementTemplate('<p>{element}</p>', "extra_$variable");
  3128. $form->addGroup([$slctFirst, $slctSecond, $slctThird], "extra_$variable", $fieldDetails['display_text']);
  3129. if ($freezeElement) {
  3130. $form->freeze('extra_'.$fieldDetails['variable']);
  3131. }
  3132. return $js;
  3133. }
  3134. }