extra_field.lib.php 134 KB

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