extra_field.lib.php 131 KB

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