extra_field.lib.php 119 KB

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