extra_field.lib.php 123 KB

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