extra_field.lib.php 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473
  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. 'data' => '',
  2044. ];
  2045. }
  2046. }
  2047. return $rules;
  2048. }
  2049. /**
  2050. * @param array $options
  2051. *
  2052. * @return array
  2053. */
  2054. public function parseConditions($options)
  2055. {
  2056. $inject_extra_fields = null;
  2057. $extraFieldOption = new ExtraFieldOption($this->type);
  2058. $double_fields = [];
  2059. if (isset($options['extra'])) {
  2060. $extra_fields = $options['extra'];
  2061. if (!empty($extra_fields)) {
  2062. $counter = 1;
  2063. foreach ($extra_fields as &$extra) {
  2064. $extra_field_obj = new ExtraField($this->type);
  2065. $extra_field_info = $extra_field_obj->get($extra['id']);
  2066. $extra['extra_field_info'] = $extra_field_info;
  2067. if (isset($extra_field_info['field_type']) &&
  2068. in_array(
  2069. $extra_field_info['field_type'],
  2070. [
  2071. self::FIELD_TYPE_SELECT,
  2072. self::FIELD_TYPE_SELECT,
  2073. self::FIELD_TYPE_DOUBLE_SELECT,
  2074. ]
  2075. )
  2076. ) {
  2077. $inject_extra_fields .= " fvo$counter.display_text as {$extra['field']}, ";
  2078. } else {
  2079. $inject_extra_fields .= " fv$counter.value as {$extra['field']}, ";
  2080. }
  2081. if (isset($extra_fields_info[$extra['id']])) {
  2082. $info = $extra_fields_info[$extra['id']];
  2083. } else {
  2084. $info = $this->get($extra['id']);
  2085. $extra_fields_info[$extra['id']] = $info;
  2086. }
  2087. if (isset($info['field_type']) && $info['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
  2088. $double_fields[$info['id']] = $info;
  2089. }
  2090. $counter++;
  2091. }
  2092. }
  2093. }
  2094. $options_by_double = [];
  2095. foreach ($double_fields as $double) {
  2096. $my_options = $extraFieldOption->get_field_options_by_field(
  2097. $double['id'],
  2098. true
  2099. );
  2100. $options_by_double['extra_'.$double['variable']] = $my_options;
  2101. }
  2102. $field_value_to_join = [];
  2103. //filter can be all/any = and/or
  2104. $inject_joins = null;
  2105. $inject_where = null;
  2106. $where = null;
  2107. if (!empty($options['where'])) {
  2108. if (!empty($options['extra'])) {
  2109. // Removing double 1=1
  2110. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  2111. // Always OR
  2112. $counter = 1;
  2113. foreach ($extra_fields as $extra_info) {
  2114. $extra_field_info = $extra_info['extra_field_info'];
  2115. $inject_joins .= " INNER JOIN $this->table_field_values fv$counter
  2116. ON (s.".$this->primaryKey." = fv$counter.".$this->handler_id.") ";
  2117. // Add options
  2118. if (isset($extra_field_info['field_type']) &&
  2119. in_array(
  2120. $extra_field_info['field_type'],
  2121. [
  2122. self::FIELD_TYPE_SELECT,
  2123. self::FIELD_TYPE_SELECT,
  2124. self::FIELD_TYPE_DOUBLE_SELECT,
  2125. ]
  2126. )
  2127. ) {
  2128. $options['where'] = str_replace(
  2129. $extra_info['field'],
  2130. 'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fvo'.$counter.'.option_value',
  2131. $options['where']
  2132. );
  2133. $inject_joins .= "
  2134. INNER JOIN $this->table_field_options fvo$counter
  2135. ON (
  2136. fv$counter.field_id = fvo$counter.field_id AND
  2137. fv$counter.value = fvo$counter.option_value
  2138. )
  2139. ";
  2140. } else {
  2141. if (isset($extra_field_info['field_type']) &&
  2142. $extra_field_info['field_type'] == self::FIELD_TYPE_TAG
  2143. ) {
  2144. $options['where'] = str_replace(
  2145. $extra_info['field'],
  2146. 'tag'.$counter.'.tag ',
  2147. $options['where']
  2148. );
  2149. $inject_joins .= "
  2150. INNER JOIN $this->table_field_rel_tag tag_rel$counter
  2151. ON (
  2152. tag_rel$counter.field_id = ".$extra_info['id']." AND
  2153. tag_rel$counter.item_id = s.".$this->primaryKey."
  2154. )
  2155. INNER JOIN $this->table_field_tag tag$counter
  2156. ON (tag$counter.id = tag_rel$counter.tag_id)
  2157. ";
  2158. } else {
  2159. //text, textarea, etc
  2160. $options['where'] = str_replace(
  2161. $extra_info['field'],
  2162. 'fv'.$counter.'.field_id = '.$extra_info['id'].' AND fv'.$counter.'.value',
  2163. $options['where']
  2164. );
  2165. }
  2166. }
  2167. $field_value_to_join[] = " fv$counter.$this->handler_id ";
  2168. $counter++;
  2169. }
  2170. if (!empty($field_value_to_join)) {
  2171. //$inject_where .= " AND s.id = ".implode(' = ', $field_value_to_join);
  2172. }
  2173. }
  2174. $where .= ' AND '.$options['where'];
  2175. }
  2176. $order = null;
  2177. if (!empty($options['order'])) {
  2178. $order = " ORDER BY ".$options['order'];
  2179. }
  2180. $limit = null;
  2181. if (!empty($options['limit'])) {
  2182. $limit = " LIMIT ".$options['limit'];
  2183. }
  2184. return [
  2185. 'order' => $order,
  2186. 'limit' => $limit,
  2187. 'where' => $where,
  2188. 'inject_where' => $inject_where,
  2189. 'inject_joins' => $inject_joins,
  2190. 'field_value_to_join' => $field_value_to_join,
  2191. 'inject_extra_fields' => $inject_extra_fields,
  2192. ];
  2193. }
  2194. //@todo move this in the display_class or somewhere else
  2195. /**
  2196. * @param $col
  2197. * @param $oper
  2198. * @param $val
  2199. *
  2200. * @return string
  2201. */
  2202. public function get_where_clause($col, $oper, $val)
  2203. {
  2204. if (empty($col)) {
  2205. return '';
  2206. }
  2207. if ($oper == 'bw' || $oper == 'bn') {
  2208. $val .= '%';
  2209. }
  2210. if ($oper == 'ew' || $oper == 'en') {
  2211. $val = '%'.$val;
  2212. }
  2213. if ($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') {
  2214. if (is_array($val)) {
  2215. $result = '"%'.implode(';', $val).'%"';
  2216. foreach ($val as $item) {
  2217. $item = trim($item);
  2218. $result .= ' OR '.$col.' LIKE "%'.$item.'%"';
  2219. }
  2220. $val = $result;
  2221. return " $col {$this->ops[$oper]} $val ";
  2222. } else {
  2223. $val = '%'.$val.'%';
  2224. }
  2225. }
  2226. $val = \Database::escape_string($val);
  2227. return " $col {$this->ops[$oper]} '$val' ";
  2228. }
  2229. /**
  2230. * @param $filters
  2231. * @param string $stringToSearch
  2232. *
  2233. * @return array
  2234. */
  2235. public function getExtraFieldRules($filters, $stringToSearch = 'extra_')
  2236. {
  2237. $extra_fields = [];
  2238. // Getting double select if exists
  2239. $double_select = [];
  2240. foreach ($filters->rules as $rule) {
  2241. if (empty($rule)) {
  2242. continue;
  2243. }
  2244. if (strpos($rule->field, '_second') === false) {
  2245. } else {
  2246. $my_field = str_replace('_second', '', $rule->field);
  2247. $double_select[$my_field] = $rule->data;
  2248. }
  2249. }
  2250. $condition_array = [];
  2251. foreach ($filters->rules as $rule) {
  2252. if (empty($rule)) {
  2253. continue;
  2254. }
  2255. if (strpos($rule->field, $stringToSearch) === false) {
  2256. // normal fields
  2257. $field = $rule->field;
  2258. if (isset($rule->data) && is_string($rule->data) && $rule->data != -1) {
  2259. $condition_array[] = $this->get_where_clause($field, $rule->op, $rule->data);
  2260. }
  2261. } else {
  2262. // Extra fields
  2263. if (strpos($rule->field, '_second') === false) {
  2264. //No _second
  2265. $original_field = str_replace($stringToSearch, '', $rule->field);
  2266. $field_option = $this->get_handler_field_info_by_field_variable($original_field);
  2267. if ($field_option['field_type'] == self::FIELD_TYPE_DOUBLE_SELECT) {
  2268. if (isset($double_select[$rule->field])) {
  2269. $data = explode('#', $rule->data);
  2270. $rule->data = $data[1].'::'.$double_select[$rule->field];
  2271. } else {
  2272. // only was sent 1 select
  2273. if (is_string($rule->data)) {
  2274. $data = explode('#', $rule->data);
  2275. $rule->data = $data[1];
  2276. }
  2277. }
  2278. if (!isset($rule->data)) {
  2279. $condition_array[] = ' ('
  2280. .$this->get_where_clause($rule->field, $rule->op, $rule->data)
  2281. .') ';
  2282. $extra_fields[] = ['field' => $rule->field, 'id' => $field_option['id']];
  2283. }
  2284. } else {
  2285. if (isset($rule->data)) {
  2286. if ($rule->data == -1) {
  2287. continue;
  2288. }
  2289. $condition_array[] = ' ('
  2290. .$this->get_where_clause($rule->field, $rule->op, $rule->data)
  2291. .') ';
  2292. $extra_fields[] = [
  2293. 'field' => $rule->field,
  2294. 'id' => $field_option['id'],
  2295. 'data' => $rule->data,
  2296. ];
  2297. }
  2298. }
  2299. } else {
  2300. $my_field = str_replace('_second', '', $rule->field);
  2301. $original_field = str_replace($stringToSearch, '', $my_field);
  2302. $field_option = $this->get_handler_field_info_by_field_variable($original_field);
  2303. $extra_fields[] = [
  2304. 'field' => $rule->field,
  2305. 'id' => $field_option['id'],
  2306. ];
  2307. }
  2308. }
  2309. }
  2310. return [
  2311. 'extra_fields' => $extra_fields,
  2312. 'condition_array' => $condition_array,
  2313. ];
  2314. }
  2315. /**
  2316. * Get the extra fields and their formatted values.
  2317. *
  2318. * @param int|string $itemId The item ID (It could be a session_id, course_id or user_id)
  2319. *
  2320. * @return array The extra fields data
  2321. */
  2322. public function getDataAndFormattedValues($itemId)
  2323. {
  2324. $valuesData = [];
  2325. $fields = $this->get_all();
  2326. $em = Database::getManager();
  2327. foreach ($fields as $field) {
  2328. if ($field['visible_to_self'] != '1') {
  2329. continue;
  2330. }
  2331. $fieldValue = new ExtraFieldValue($this->type);
  2332. $valueData = $fieldValue->get_values_by_handler_and_field_id(
  2333. $itemId,
  2334. $field['id'],
  2335. true
  2336. );
  2337. if ($field['field_type'] == ExtraField::FIELD_TYPE_TAG) {
  2338. $tags = $em
  2339. ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  2340. ->findBy(
  2341. [
  2342. 'fieldId' => $field['id'],
  2343. 'itemId' => $itemId,
  2344. ]
  2345. );
  2346. if ($tags) {
  2347. /** @var \Chamilo\CoreBundle\Entity\ExtraFieldRelTag $tag */
  2348. $data = [];
  2349. foreach ($tags as $extraFieldTag) {
  2350. /** @var \Chamilo\CoreBundle\Entity\Tag $tag */
  2351. $tag = $em->find('ChamiloCoreBundle:Tag', $extraFieldTag->getTagId());
  2352. /*$data[] = [
  2353. 'id' => $extraFieldTag->getTagId(),
  2354. 'value' => $tag->getTag()
  2355. ];*/
  2356. $data[] = $tag->getTag();
  2357. }
  2358. $valueData = implode(',', $data);
  2359. }
  2360. }
  2361. if (!$valueData) {
  2362. continue;
  2363. }
  2364. $displayedValue = get_lang('None');
  2365. switch ($field['field_type']) {
  2366. case self::FIELD_TYPE_CHECKBOX:
  2367. if ($valueData !== false && $valueData['value'] == '1') {
  2368. $displayedValue = get_lang('Yes');
  2369. } else {
  2370. $displayedValue = get_lang('No');
  2371. }
  2372. break;
  2373. case self::FIELD_TYPE_DATE:
  2374. if ($valueData !== false && !empty($valueData['value'])) {
  2375. $displayedValue = api_format_date($valueData['value'], DATE_FORMAT_LONG_NO_DAY);
  2376. }
  2377. break;
  2378. case self::FIELD_TYPE_TAG:
  2379. if (!empty($valueData)) {
  2380. $displayedValue = $valueData;
  2381. }
  2382. break;
  2383. case self::FIELD_TYPE_FILE_IMAGE:
  2384. if ($valueData === false || empty($valueData['value'])) {
  2385. break;
  2386. }
  2387. if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
  2388. break;
  2389. }
  2390. $image = Display::img(
  2391. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2392. $field['display_text'],
  2393. ['width' => '300']
  2394. );
  2395. $displayedValue = Display::url(
  2396. $image,
  2397. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2398. ['target' => '_blank']
  2399. );
  2400. break;
  2401. case self::FIELD_TYPE_FILE:
  2402. if ($valueData === false || empty($valueData['value'])) {
  2403. break;
  2404. }
  2405. if (!file_exists(api_get_path(SYS_UPLOAD_PATH).$valueData['value'])) {
  2406. break;
  2407. }
  2408. $displayedValue = Display::url(
  2409. get_lang('Download'),
  2410. api_get_path(WEB_UPLOAD_PATH).$valueData['value'],
  2411. [
  2412. 'title' => $field['display_text'],
  2413. 'target' => '_blank',
  2414. ]
  2415. );
  2416. break;
  2417. default:
  2418. $displayedValue = $valueData['value'];
  2419. break;
  2420. }
  2421. $valuesData[] = [
  2422. 'text' => $field['display_text'],
  2423. 'value' => $displayedValue,
  2424. ];
  2425. }
  2426. return $valuesData;
  2427. }
  2428. /**
  2429. * Gets an element.
  2430. *
  2431. * @param int $id
  2432. * @param bool $translateDisplayText Optional
  2433. *
  2434. * @return array
  2435. */
  2436. public function get($id, $translateDisplayText = true)
  2437. {
  2438. $info = parent::get($id);
  2439. if ($translateDisplayText) {
  2440. $info['display_text'] = self::translateDisplayName($info['variable'], $info['display_text']);
  2441. }
  2442. return $info;
  2443. }
  2444. /**
  2445. * Translate the display text for a extra field.
  2446. *
  2447. * @param string $variable
  2448. * @param string $defaultDisplayText
  2449. *
  2450. * @return string
  2451. */
  2452. public static function translateDisplayName($variable, $defaultDisplayText)
  2453. {
  2454. $camelCase = api_underscore_to_camel_case($variable);
  2455. return isset($GLOBALS[$camelCase]) ? $GLOBALS[$camelCase] : $defaultDisplayText;
  2456. }
  2457. /**
  2458. * @param int $fieldId
  2459. * @param string $tag
  2460. *
  2461. * @return array
  2462. */
  2463. public function getAllUserPerTag($fieldId, $tag)
  2464. {
  2465. $tagRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2466. $tag = Database::escape_string($tag);
  2467. $fieldId = (int) $fieldId;
  2468. $sql = "SELECT user_id
  2469. FROM {$this->table_field_tag} f INNER JOIN $tagRelUserTable ft
  2470. ON tag_id = f.id
  2471. WHERE tag = '$tag' AND f.field_id = $fieldId;
  2472. ";
  2473. $result = Database::query($sql);
  2474. return Database::store_result($result, 'ASSOC');
  2475. }
  2476. /**
  2477. * @param int $fieldId
  2478. * @param int $tagId
  2479. *
  2480. * @return array
  2481. */
  2482. public function getAllSkillPerTag($fieldId, $tagId)
  2483. {
  2484. $skillTable = Database::get_main_table(TABLE_MAIN_SKILL);
  2485. $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
  2486. $fieldId = intval($fieldId);
  2487. $tagId = intval($tagId);
  2488. $sql = "SELECT s.id
  2489. FROM $skillTable s INNER JOIN $tagRelExtraTable t
  2490. ON t.item_id = s.id
  2491. WHERE tag_id = $tagId AND t.field_id = $fieldId;
  2492. ";
  2493. $result = Database::query($sql);
  2494. $result = Database::store_result($result, 'ASSOC');
  2495. $skillList = [];
  2496. foreach ($result as $index => $value) {
  2497. $skillList[$value['id']] = $value['id'];
  2498. }
  2499. return $skillList;
  2500. }
  2501. /**
  2502. * @param string $from
  2503. * @param string $search
  2504. * @param array $options
  2505. *
  2506. * @return array
  2507. */
  2508. public function searchOptionsFromTags($from, $search, $options)
  2509. {
  2510. $extraFieldInfo = $this->get_handler_field_info_by_field_variable(
  2511. str_replace('extra_', '', $from)
  2512. );
  2513. $extraFieldInfoTag = $this->get_handler_field_info_by_field_variable(
  2514. str_replace('extra_', '', $search)
  2515. );
  2516. if (empty($extraFieldInfo) || empty($extraFieldInfoTag)) {
  2517. return [];
  2518. }
  2519. $id = $extraFieldInfo['id'];
  2520. $tagId = $extraFieldInfoTag['id'];
  2521. $table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  2522. $tagRelExtraTable = Database::get_main_table(TABLE_MAIN_EXTRA_FIELD_REL_TAG);
  2523. $tagTable = Database::get_main_table(TABLE_MAIN_TAG);
  2524. $optionsTable = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  2525. $sql = "SELECT DISTINCT t.*, v.value, o.display_text
  2526. FROM $tagRelExtraTable te
  2527. INNER JOIN $tagTable t
  2528. ON (t.id = te.tag_id AND te.field_id = t.field_id AND te.field_id = $tagId)
  2529. INNER JOIN $table v
  2530. ON (te.item_id = v.item_id AND v.field_id = $id)
  2531. INNER JOIN $optionsTable o
  2532. ON (o.option_value = v.value)
  2533. WHERE v.value IN ('".implode("','", $options)."')
  2534. ORDER BY o.option_order, t.tag
  2535. ";
  2536. $result = Database::query($sql);
  2537. $result = Database::store_result($result);
  2538. return $result;
  2539. }
  2540. /**
  2541. * @param string $variable
  2542. * @param string $dataValue
  2543. *
  2544. * @return string
  2545. */
  2546. public static function getLocalizationJavascript($variable, $dataValue)
  2547. {
  2548. $dataValue = addslashes($dataValue);
  2549. $html = "<script>
  2550. $(function() {
  2551. if (typeof google === 'object') {
  2552. var address = '$dataValue';
  2553. initializeGeo{$variable}(address, false);
  2554. $('#geolocalization_extra_{$variable}').on('click', function() {
  2555. var address = $('#{$variable}').val();
  2556. initializeGeo{$variable}(address, false);
  2557. return false;
  2558. });
  2559. $('#myLocation_extra_{$variable}').on('click', function() {
  2560. myLocation{$variable}();
  2561. return false;
  2562. });
  2563. // When clicking enter
  2564. $('#{$variable}').keypress(function(event) {
  2565. if (event.which == 13) {
  2566. $('#geolocalization_extra_{$variable}').click();
  2567. return false;
  2568. }
  2569. });
  2570. // On focus out update city
  2571. $('#{$variable}').focusout(function() {
  2572. $('#geolocalization_extra_{$variable}').click();
  2573. return false;
  2574. });
  2575. return;
  2576. }
  2577. $('#map_extra_{$variable}')
  2578. .html('<div class=\"alert alert-info\">"
  2579. .addslashes(get_lang('YouNeedToActivateTheGoogleMapsPluginInAdminPlatformToSeeTheMap'))
  2580. ."</div>');
  2581. });
  2582. function myLocation{$variable}()
  2583. {
  2584. if (navigator.geolocation) {
  2585. var geoPosition = function(position) {
  2586. var lat = position.coords.latitude;
  2587. var lng = position.coords.longitude;
  2588. var latLng = new google.maps.LatLng(lat, lng);
  2589. initializeGeo{$variable}(false, latLng);
  2590. };
  2591. var geoError = function(error) {
  2592. alert('Geocode ".get_lang('Error').": ' + error);
  2593. };
  2594. var geoOptions = {
  2595. enableHighAccuracy: true
  2596. };
  2597. navigator.geolocation.getCurrentPosition(geoPosition, geoError, geoOptions);
  2598. }
  2599. }
  2600. function initializeGeo{$variable}(address, latLng)
  2601. {
  2602. var geocoder = new google.maps.Geocoder();
  2603. var latlng = new google.maps.LatLng(-34.397, 150.644);
  2604. var myOptions = {
  2605. zoom: 15,
  2606. center: latlng,
  2607. mapTypeControl: true,
  2608. mapTypeControlOptions: {
  2609. style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  2610. },
  2611. navigationControl: true,
  2612. mapTypeId: google.maps.MapTypeId.ROADMAP
  2613. };
  2614. map_{$variable} = new google.maps.Map(
  2615. document.getElementById('map_extra_{$variable}'),
  2616. myOptions
  2617. );
  2618. var parameter = address ? {'address': address} : latLng ? {'latLng': latLng} : false;
  2619. if (geocoder && parameter) {
  2620. geocoder.geocode(parameter, function(results, status) {
  2621. if (status == google.maps.GeocoderStatus.OK) {
  2622. if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  2623. map_{$variable}.setCenter(results[0].geometry.location);
  2624. // get city and country
  2625. var defaultAddress = results[0].formatted_address;
  2626. var city = '';
  2627. var country = '';
  2628. for (var i=0; i<results[0].address_components.length; i++) {
  2629. if (results[0].address_components[i].types[0] == \"locality\") {
  2630. //this is the object you are looking for City
  2631. city = results[0].address_components[i];
  2632. }
  2633. /*if (results[j].address_components[i].types[0] == \"administrative_area_level_1\") {
  2634. //this is the object you are looking for State
  2635. region = results[0].address_components[i];
  2636. }*/
  2637. if (results[0].address_components[i].types[0] == \"country\") {
  2638. //this is the object you are looking for
  2639. country = results[0].address_components[i];
  2640. }
  2641. }
  2642. if (city && city.long_name && country && country.long_name) {
  2643. defaultAddress = city.long_name + ', ' + country.long_name;
  2644. }
  2645. $('#{$variable}').val(defaultAddress);
  2646. $('#{$variable}_coordinates').val(
  2647. results[0].geometry.location.lat()+','+results[0].geometry.location.lng()
  2648. );
  2649. var infowindow = new google.maps.InfoWindow({
  2650. content: '<b>' + $('#extra_{$variable}').val() + '</b>',
  2651. size: new google.maps.Size(150, 50)
  2652. });
  2653. var marker = new google.maps.Marker({
  2654. position: results[0].geometry.location,
  2655. map: map_{$variable},
  2656. title: $('#extra_{$variable}').val()
  2657. });
  2658. google.maps.event.addListener(marker, 'click', function() {
  2659. infowindow.open(map_{$variable}, marker);
  2660. });
  2661. } else {
  2662. alert('".get_lang('NotFound')."');
  2663. }
  2664. } else {
  2665. alert('Geocode ".get_lang('Error').": ".get_lang("AddressField")." ".get_lang('NotFound')."');
  2666. }
  2667. });
  2668. }
  2669. }
  2670. </script>";
  2671. return $html;
  2672. }
  2673. /**
  2674. * @param string $variable
  2675. * @param string $text
  2676. *
  2677. * @return string
  2678. */
  2679. public static function getLocalizationInput($variable, $text)
  2680. {
  2681. $html = '
  2682. <div class="form-group">
  2683. <label for="geolocalization_extra_'.$variable.'"
  2684. class="col-sm-2 control-label"></label>
  2685. <div class="col-sm-8">
  2686. <button class="btn btn-default"
  2687. id="geolocalization_extra_'.$variable.'"
  2688. name="geolocalization_extra_'.$variable.'"
  2689. type="submit">
  2690. <em class="fa fa-map-marker"></em> '.get_lang('SearchGeolocalization').'
  2691. </button>
  2692. <button class="btn btn-default" id="myLocation_extra_'.$variable.'"
  2693. name="myLocation_extra_'.$variable.'"
  2694. type="submit">
  2695. <em class="fa fa-crosshairs"></em> '.get_lang('MyLocation').'
  2696. </button>
  2697. </div>
  2698. </div>
  2699. <div class="form-group">
  2700. <label for="map_extra_'.$variable.'" class="col-sm-2 control-label">
  2701. '.$text.' - '.get_lang('Map').'
  2702. </label>
  2703. <div class="col-sm-8">
  2704. <div name="map_extra_'.$variable.'"
  2705. id="map_extra_'.$variable.'" style="width:100%; height:300px;">
  2706. </div>
  2707. </div>
  2708. </div>
  2709. ';
  2710. return $html;
  2711. }
  2712. /**
  2713. * @param array $options
  2714. * @param int $parentId
  2715. *
  2716. * @return array
  2717. */
  2718. private static function getOptionsFromTripleSelect(array $options, $parentId)
  2719. {
  2720. return array_filter($options, function ($option) use ($parentId) {
  2721. return $option['option_value'] == $parentId;
  2722. });
  2723. }
  2724. /**
  2725. * @param \FormValidator $form
  2726. * @param array $fieldDetails
  2727. * @param int $defaultValueId
  2728. * @param bool $freezeElement
  2729. */
  2730. private function addSelectElement(FormValidator $form, array $fieldDetails, $defaultValueId, $freezeElement = false)
  2731. {
  2732. $get_lang_variables = false;
  2733. if (in_array(
  2734. $fieldDetails['variable'],
  2735. ['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
  2736. )) {
  2737. $get_lang_variables = true;
  2738. }
  2739. // Get extra field workflow
  2740. $addOptions = [];
  2741. $optionsExists = false;
  2742. $options = [];
  2743. $optionList = [];
  2744. if (!empty($fieldDetails['options'])) {
  2745. foreach ($fieldDetails['options'] as $option_details) {
  2746. $optionList[$option_details['id']] = $option_details;
  2747. if ($get_lang_variables) {
  2748. $options[$option_details['option_value']] = $option_details['display_text'];
  2749. } else {
  2750. if ($optionsExists) {
  2751. // Adding always the default value
  2752. if ($option_details['id'] == $defaultValueId) {
  2753. $options[$option_details['option_value']] = $option_details['display_text'];
  2754. } else {
  2755. if (isset($addOptions) && !empty($addOptions)) {
  2756. // Parsing filters
  2757. if (in_array($option_details['id'], $addOptions)) {
  2758. $options[$option_details['option_value']] = $option_details['display_text'];
  2759. }
  2760. }
  2761. }
  2762. } else {
  2763. // Normal behaviour
  2764. $options[$option_details['option_value']] = $option_details['display_text'];
  2765. }
  2766. }
  2767. }
  2768. // Setting priority message
  2769. if (isset($optionList[$defaultValueId])
  2770. && isset($optionList[$defaultValueId]['priority'])
  2771. ) {
  2772. if (!empty($optionList[$defaultValueId]['priority'])) {
  2773. $priorityId = $optionList[$defaultValueId]['priority'];
  2774. $option = new ExtraFieldOption($this->type);
  2775. $messageType = $option->getPriorityMessageType($priorityId);
  2776. $form->addElement(
  2777. 'label',
  2778. null,
  2779. Display::return_message(
  2780. $optionList[$defaultValueId]['priority_message'],
  2781. $messageType
  2782. )
  2783. );
  2784. }
  2785. }
  2786. }
  2787. /** @var \HTML_QuickForm_select $slct */
  2788. $slct = $form->addElement(
  2789. 'select',
  2790. 'extra_'.$fieldDetails['variable'],
  2791. $fieldDetails['display_text'],
  2792. [],
  2793. ['id' => 'extra_'.$fieldDetails['variable']]
  2794. );
  2795. if (empty($defaultValueId)) {
  2796. $slct->addOption(get_lang('SelectAnOption'), '');
  2797. }
  2798. foreach ($options as $value => $text) {
  2799. if (empty($value)) {
  2800. $slct->addOption($text, $value);
  2801. continue;
  2802. }
  2803. $valueParts = explode('#', $text);
  2804. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  2805. $slct->addOption(implode('', $valueParts), $value, ['data-value' => $dataValue]);
  2806. }
  2807. /* Enable this when field_loggeable is introduced as a table field (2.0)
  2808. if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
  2809. $form->addElement(
  2810. 'textarea',
  2811. 'extra_' . $field_details['variable'] . '_comment',
  2812. $field_details['display_text'] . ' ' . get_lang('Comment')
  2813. );
  2814. $extraFieldValue = new ExtraFieldValue($this->type);
  2815. $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
  2816. $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
  2817. $newEntity = $repo->findOneBy(
  2818. array(
  2819. $this->handlerEntityId => $itemId,
  2820. 'fieldId' => $field_details['id']
  2821. )
  2822. );
  2823. // @todo move this in a function inside the class
  2824. if ($newEntity) {
  2825. $logs = $repoLog->getLogEntries($newEntity);
  2826. if (!empty($logs)) {
  2827. $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />';
  2828. $table = new HTML_Table(array('class' => 'data_table'));
  2829. $table->setHeaderContents(0, 0, get_lang('Value'));
  2830. $table->setHeaderContents(0, 1, get_lang('Comment'));
  2831. $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
  2832. $table->setHeaderContents(0, 3, get_lang('Username'));
  2833. $row = 1;
  2834. foreach ($logs as $log) {
  2835. $column = 0;
  2836. $data = $log->getData();
  2837. $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
  2838. $comment = isset($data['comment']) ? $data['comment'] : null;
  2839. $table->setCellContents($row, $column, $fieldValue);
  2840. $column++;
  2841. $table->setCellContents($row, $column, $comment);
  2842. $column++;
  2843. $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
  2844. $column++;
  2845. $table->setCellContents($row, $column, $log->getUsername());
  2846. $row++;
  2847. }
  2848. $form->addElement('label', null, $html.$table->toHtml());
  2849. }
  2850. }
  2851. }
  2852. */
  2853. if ($freezeElement) {
  2854. $form->freeze('extra_'.$fieldDetails['variable']);
  2855. }
  2856. }
  2857. /**
  2858. * @param \FormValidator $form
  2859. * @param array $fieldDetails
  2860. * @param array $extraData
  2861. * @param bool $freezeElement
  2862. *
  2863. * @return string JavaScript code
  2864. */
  2865. private function addDoubleSelectElement(FormValidator $form, $fieldDetails, $extraData, $freezeElement = false)
  2866. {
  2867. $firstSelectId = 'first_extra_'.$fieldDetails['variable'];
  2868. $secondSelectId = 'second_extra_'.$fieldDetails['variable'];
  2869. $jqueryReadyContent = "
  2870. $('#$firstSelectId').on('change', function() {
  2871. var id = $(this).val();
  2872. if (!id) {
  2873. $('#$secondSelectId').empty().selectpicker('refresh');
  2874. return;
  2875. }
  2876. $.getJSON(_p.web_ajax + 'extra_field.ajax.php?1=1&a=get_second_select_options', {
  2877. 'type': '{$this->type}',
  2878. 'field_id': {$fieldDetails['id']},
  2879. 'option_value_id': id
  2880. })
  2881. .done(function(data) {
  2882. $('#$secondSelectId').empty();
  2883. $.each(data, function(index, value) {
  2884. $('#second_extra_{$fieldDetails['variable']}').append(
  2885. $('<option>', {value: index, text: value})
  2886. );
  2887. });
  2888. $('#$secondSelectId').selectpicker('refresh');
  2889. });
  2890. });
  2891. ";
  2892. $firstId = null;
  2893. if (!empty($extraData)) {
  2894. if (isset($extraData['extra_'.$fieldDetails['variable']])) {
  2895. $firstId = $extraData['extra_'.$fieldDetails['variable']]['extra_'.$fieldDetails['variable']];
  2896. }
  2897. }
  2898. $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
  2899. $values = ['' => get_lang('Select')];
  2900. $second_values = [];
  2901. if (!empty($options)) {
  2902. foreach ($options as $option) {
  2903. foreach ($option as $sub_option) {
  2904. if ($sub_option['option_value'] == '0') {
  2905. $values[$sub_option['id']] = $sub_option['display_text'];
  2906. continue;
  2907. }
  2908. if ($firstId === $sub_option['option_value']) {
  2909. $second_values[$sub_option['id']] = $sub_option['display_text'];
  2910. }
  2911. }
  2912. }
  2913. }
  2914. $form
  2915. ->defaultRenderer()
  2916. ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
  2917. $group = [];
  2918. $group[] = $form->createElement(
  2919. 'select',
  2920. 'extra_'.$fieldDetails['variable'],
  2921. null,
  2922. $values,
  2923. ['id' => $firstSelectId]
  2924. );
  2925. $group[] = $form->createElement(
  2926. 'select',
  2927. 'extra_'.$fieldDetails['variable'].'_second',
  2928. null,
  2929. $second_values,
  2930. ['id' => $secondSelectId]
  2931. );
  2932. $form->addGroup(
  2933. $group,
  2934. 'extra_'.$fieldDetails['variable'],
  2935. $fieldDetails['display_text']
  2936. );
  2937. if ($freezeElement) {
  2938. $form->freeze('extra_'.$fieldDetails['variable']);
  2939. }
  2940. return $jqueryReadyContent;
  2941. }
  2942. /**
  2943. * @param \FormValidator $form
  2944. * @param array $fieldDetails
  2945. * @param bool $freezeElement Optional
  2946. *
  2947. * @return string JavaScript code
  2948. */
  2949. private function addSelectWithTextFieldElement(
  2950. FormValidator $form,
  2951. array $fieldDetails,
  2952. $freezeElement = false
  2953. ) {
  2954. $firstSelectId = 'slct_extra_'.$fieldDetails['variable'];
  2955. $txtSelectId = 'txt_extra_'.$fieldDetails['variable'];
  2956. $jqueryReadyContent = "
  2957. $('#$firstSelectId').on('change', function() {
  2958. var id = $(this).val();
  2959. if (!id) {
  2960. $('#$txtSelectId').val('');
  2961. }
  2962. });
  2963. ";
  2964. $options = $this->extra_field_double_select_convert_array_to_ordered_array($fieldDetails['options']);
  2965. $values = ['' => get_lang('Select')];
  2966. if (!empty($options)) {
  2967. foreach ($options as $option) {
  2968. foreach ($option as $sub_option) {
  2969. if ($sub_option['option_value'] != '0') {
  2970. continue;
  2971. }
  2972. $values[$sub_option['id']] = $sub_option['display_text'];
  2973. }
  2974. }
  2975. }
  2976. $form
  2977. ->defaultRenderer()
  2978. ->setGroupElementTemplate('<p>{element}</p>', 'extra_'.$fieldDetails['variable']);
  2979. $group = [];
  2980. $group[] = $form->createElement(
  2981. 'select',
  2982. 'extra_'.$fieldDetails['variable'],
  2983. null,
  2984. $values,
  2985. ['id' => $firstSelectId]
  2986. );
  2987. $group[] = $form->createElement(
  2988. 'text',
  2989. 'extra_'.$fieldDetails['variable'].'_second',
  2990. null,
  2991. ['id' => $txtSelectId]
  2992. );
  2993. $form->addGroup(
  2994. $group,
  2995. 'extra_'.$fieldDetails['variable'],
  2996. $fieldDetails['display_text']
  2997. );
  2998. if ($freezeElement) {
  2999. $form->freeze('extra_'.$fieldDetails['variable']);
  3000. }
  3001. return $jqueryReadyContent;
  3002. }
  3003. /**
  3004. * @param \FormValidator $form
  3005. * @param array $fieldDetails
  3006. * @param array $extraData
  3007. * @param bool $freezeElement
  3008. *
  3009. * @return string
  3010. */
  3011. private function addTripleSelectElement(
  3012. FormValidator $form,
  3013. array $fieldDetails,
  3014. array $extraData,
  3015. $freezeElement
  3016. ) {
  3017. $variable = $fieldDetails['variable'];
  3018. $id = $fieldDetails['id'];
  3019. $slctFirstId = "first_extra$variable";
  3020. $slctSecondId = "second_extra$variable";
  3021. $slctThirdId = "third_extra$variable";
  3022. $langSelect = get_lang('Select');
  3023. $js = "
  3024. (function () {
  3025. var slctFirst = $('#$slctFirstId'),
  3026. slctSecond = $('#$slctSecondId'),
  3027. slctThird = $('#$slctThirdId');
  3028. slctFirst.on('change', function () {
  3029. slctSecond.empty().selectpicker('refresh');
  3030. slctThird.empty().selectpicker('refresh');
  3031. var level = $(this).val();
  3032. if (!level) {
  3033. return;
  3034. }
  3035. $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
  3036. 'a': 'get_second_select_options',
  3037. 'type': '$this->type',
  3038. 'field_id': $id,
  3039. 'option_value_id': level
  3040. })
  3041. .done(function (data) {
  3042. slctSecond.append(
  3043. $('<option>', {value: '', text: '$langSelect'})
  3044. );
  3045. $.each(data, function (index, value) {
  3046. var valueParts = value.split('#'),
  3047. dataValue = valueParts.length > 1 ? valueParts.shift() : '';
  3048. slctSecond.append(
  3049. $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
  3050. );
  3051. });
  3052. slctSecond.selectpicker('refresh');
  3053. });
  3054. });
  3055. slctSecond.on('change', function () {
  3056. slctThird.empty().selectpicker('refresh');
  3057. var level = $(this).val();
  3058. if (!level) {
  3059. return;
  3060. }
  3061. $.getJSON(_p.web_ajax + 'extra_field.ajax.php', {
  3062. 'a': 'get_second_select_options',
  3063. 'type': '$this->type',
  3064. 'field_id': $id,
  3065. 'option_value_id': level
  3066. })
  3067. .done(function (data) {
  3068. slctThird.append(
  3069. $('<option>', {value: '', text: '$langSelect'})
  3070. );
  3071. $.each(data, function (index, value) {
  3072. var valueParts = value.split('#'),
  3073. dataValue = valueParts.length > 1 ? valueParts.shift() : '';
  3074. slctThird.append(
  3075. $('<option>', {value: index, text: valueParts.join(''), 'data-value': dataValue})
  3076. );
  3077. });
  3078. slctThird.selectpicker('refresh');
  3079. });
  3080. });
  3081. })();
  3082. ";
  3083. $firstId = isset($extraData["extra_$variable"]["extra_$variable"])
  3084. ? $extraData["extra_$variable"]["extra_$variable"]
  3085. : '';
  3086. $secondId = isset($extraData["extra_$variable"]["extra_{$variable}_second"])
  3087. ? $extraData["extra_$variable"]["extra_{$variable}_second"]
  3088. : '';
  3089. $options = $this->tripleSelectConvertArrayToOrderedArray($fieldDetails['options']);
  3090. $values1 = ['' => $langSelect];
  3091. $values2 = ['' => $langSelect];
  3092. $values3 = ['' => $langSelect];
  3093. $level1 = $this->getOptionsFromTripleSelect($options['level1'], 0);
  3094. $level2 = $this->getOptionsFromTripleSelect($options['level2'], $firstId);
  3095. $level3 = $this->getOptionsFromTripleSelect($options['level3'], $secondId);
  3096. /** @var \HTML_QuickForm_select $slctFirst */
  3097. $slctFirst = $form->createElement('select', "extra_$variable", null, $values1, ['id' => $slctFirstId]);
  3098. /** @var \HTML_QuickForm_select $slctFirst */
  3099. $slctSecond = $form->createElement('select', "extra_{$variable}_second", null, $values2, ['id' => $slctSecondId]);
  3100. /** @var \HTML_QuickForm_select $slctFirst */
  3101. $slctThird = $form->createElement('select', "extra_{$variable}_third", null, $values3, ['id' => $slctThirdId]);
  3102. foreach ($level1 as $item1) {
  3103. $valueParts = explode('#', $item1['display_text']);
  3104. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3105. $slctFirst->addOption(implode('', $valueParts), $item1['id'], ['data-value' => $dataValue]);
  3106. }
  3107. foreach ($level2 as $item2) {
  3108. $valueParts = explode('#', $item2['display_text']);
  3109. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3110. $slctSecond->addOption(implode('', $valueParts), $item2['id'], ['data-value' => $dataValue]);
  3111. }
  3112. foreach ($level3 as $item3) {
  3113. $valueParts = explode('#', $item3['display_text']);
  3114. $dataValue = count($valueParts) > 1 ? array_shift($valueParts) : '';
  3115. $slctThird->addOption(implode('', $valueParts), $item3['id'], ['data-value' => $dataValue]);
  3116. }
  3117. $form
  3118. ->defaultRenderer()
  3119. ->setGroupElementTemplate('<p>{element}</p>', "extra_$variable");
  3120. $form->addGroup([$slctFirst, $slctSecond, $slctThird], "extra_$variable", $fieldDetails['display_text']);
  3121. if ($freezeElement) {
  3122. $form->freeze('extra_'.$fieldDetails['variable']);
  3123. }
  3124. return $js;
  3125. }
  3126. }