extra_field.lib.php 134 KB

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