extra_field.lib.php 134 KB

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