extra_field.lib.php 120 KB

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