extra_field.lib.php 135 KB

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