extra_field.lib.php 135 KB

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