extra_field_value.lib.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use Chamilo\CoreBundle\Entity\Tag;
  5. use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
  6. use Chamilo\CoreBundle\Entity\ExtraFieldValues;
  7. /**
  8. * Class ExtraFieldValue
  9. * Declaration for the ExtraFieldValue class, managing the values in extra
  10. * fields for any data type
  11. *
  12. * @package chamilo.library
  13. *
  14. */
  15. class ExtraFieldValue extends Model
  16. {
  17. public $type = '';
  18. public $columns = array(
  19. 'id',
  20. 'field_id',
  21. 'value',
  22. 'comment',
  23. 'item_id',
  24. 'created_at',
  25. 'updated_at',
  26. );
  27. /** @var ExtraField */
  28. public $extraField;
  29. /**
  30. * Formats the necessary elements for the given datatype
  31. * @param string $type The type of data to which this extra field
  32. * applies (user, course, session, ...)
  33. *
  34. * @assert (-1) === false
  35. */
  36. public function __construct($type)
  37. {
  38. parent::__construct();
  39. $this->type = $type;
  40. $extraField = new ExtraField($this->type);
  41. $this->extraField = $extraField;
  42. $this->table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  43. $this->table_handler_field = Database::get_main_table(TABLE_EXTRA_FIELD);
  44. }
  45. /**
  46. * @return ExtraField
  47. */
  48. public function getExtraField()
  49. {
  50. return $this->extraField;
  51. }
  52. /**
  53. * Gets the number of values stored in the table (all fields together)
  54. * for this type of resource
  55. * @return integer Number of rows in the table
  56. * @assert () !== false
  57. */
  58. public function get_count()
  59. {
  60. $em = Database::getManager();
  61. $query = $em->getRepository('ChamiloCoreBundle:ExtraFieldValues')->createQueryBuilder('e');
  62. $query->select('count(e.id)');
  63. $query->where('e.extraFieldType = :type');
  64. $query->setParameter('type', $this->getExtraField()->getExtraFieldType());
  65. return $query->getQuery()->getSingleScalarResult();
  66. }
  67. /**
  68. * Save the extra fields values
  69. * In order to save this function needs a item_id (user id, course id, etc)
  70. * This function is used with $extraField->addElements()
  71. * @param array $params array for the insertion into the *_field_values table
  72. * @param bool $onlySubmittedFields Only save parameters in the $param array
  73. * @param bool $showQuery
  74. * @return mixed false on empty params, void otherwise
  75. * @assert (array()) === false
  76. */
  77. public function saveFieldValues($params, $onlySubmittedFields = false, $showQuery = false)
  78. {
  79. foreach ($params as $key => $value) {
  80. $found = strpos($key, '__persist__');
  81. if ($found === false) {
  82. continue;
  83. }
  84. $tempKey = str_replace('__persist__', '', $key);
  85. if (!isset($params[$tempKey])) {
  86. $params[$tempKey] = array();
  87. }
  88. }
  89. if (empty($params['item_id'])) {
  90. return false;
  91. }
  92. $type = $this->getExtraField()->getExtraFieldType();
  93. $extraField = new ExtraField($this->type);
  94. $extraFields = $extraField->get_all(null, 'option_order');
  95. // Parse params.
  96. foreach ($extraFields as $fieldDetails) {
  97. $field_variable = $fieldDetails['variable'];
  98. // if the field is not visible to the user in the end, we need to apply special rules
  99. if ($fieldDetails['visible_to_self'] != 1) {
  100. //only admins should be able to add those values
  101. if (!api_is_platform_admin(true, true)) {
  102. // although if not admin but sent through a CLI script, we should accept it as well
  103. if (PHP_SAPI != 'cli') {
  104. continue; //not a CLI script, so don't write the value to DB
  105. }
  106. }
  107. }
  108. if ($onlySubmittedFields && !isset($params['extra_'.$field_variable])) {
  109. continue;
  110. }
  111. if (isset($params['extra_'.$field_variable])) {
  112. $value = $params['extra_'.$field_variable];
  113. } else {
  114. $value = '';
  115. }
  116. $extraFieldInfo = $this->getExtraField()->get_handler_field_info_by_field_variable($field_variable);
  117. if (!$extraFieldInfo) {
  118. continue;
  119. }
  120. $commentVariable = 'extra_'.$field_variable.'_comment';
  121. $comment = isset($params[$commentVariable]) ? $params[$commentVariable] : null;
  122. $dirPermissions = api_get_permissions_for_new_directories();
  123. switch ($extraFieldInfo['field_type']) {
  124. case ExtraField::FIELD_TYPE_TAG:
  125. if ($type == EntityExtraField::USER_FIELD_TYPE) {
  126. UserManager::delete_user_tags(
  127. $params['item_id'],
  128. $extraFieldInfo['id']
  129. );
  130. UserManager::process_tags(
  131. $value,
  132. $params['item_id'],
  133. $extraFieldInfo['id']
  134. );
  135. break;
  136. }
  137. $em = Database::getManager();
  138. $currentTags = $em
  139. ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  140. ->findBy([
  141. 'fieldId' => $extraFieldInfo['id'],
  142. 'itemId' => $params['item_id']
  143. ]);
  144. foreach ($currentTags as $extraFieldtag) {
  145. $em->remove($extraFieldtag);
  146. }
  147. $em->flush();
  148. $tagValues = is_array($value) ? $value : [$value];
  149. $tags = [];
  150. foreach ($tagValues as $tagValue) {
  151. if (empty($tagValue)) {
  152. continue;
  153. }
  154. $tagsResult = $em->getRepository('ChamiloCoreBundle:Tag')
  155. ->findBy([
  156. 'tag' => $tagValue,
  157. 'fieldId' => $extraFieldInfo['id']
  158. ]);
  159. if (empty($tagsResult)) {
  160. $tag = new Tag();
  161. $tag->setFieldId($extraFieldInfo['id']);
  162. $tag->setTag($tagValue);
  163. $tags[] = $tag;
  164. } else {
  165. $tags = array_merge($tags, $tagsResult);
  166. }
  167. }
  168. foreach ($tags as $tag) {
  169. $tagUses = $em
  170. ->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')
  171. ->findBy([
  172. 'tagId' => $tag->getId()
  173. ]);
  174. $tag->setCount(count($tagUses) + 1);
  175. $em->persist($tag);
  176. }
  177. $em->flush();
  178. foreach ($tags as $tag) {
  179. $fieldRelTag = new ExtraFieldRelTag();
  180. $fieldRelTag->setFieldId($extraFieldInfo['id']);
  181. $fieldRelTag->setItemId($params['item_id']);
  182. $fieldRelTag->setTagId($tag->getId());
  183. $em->persist($fieldRelTag);
  184. }
  185. $em->flush();
  186. break;
  187. case ExtraField::FIELD_TYPE_FILE_IMAGE:
  188. switch ($this->type) {
  189. case 'course':
  190. $fileDir = api_get_path(SYS_UPLOAD_PATH)."courses/";
  191. $fileDirStored = "courses/";
  192. break;
  193. case 'session':
  194. $fileDir = api_get_path(SYS_UPLOAD_PATH)."sessions/";
  195. $fileDirStored = "sessions/";
  196. break;
  197. case 'user':
  198. $fileDir = UserManager::getUserPathById($params['item_id'], 'system');
  199. $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last');
  200. break;
  201. case 'work':
  202. $fileDir = api_get_path(SYS_UPLOAD_PATH).'work/';
  203. $fileDirStored = 'work/';
  204. break;
  205. }
  206. $fileName = ExtraField::FIELD_TYPE_FILE_IMAGE."_{$params['item_id']}.png";
  207. if (!file_exists($fileDir)) {
  208. mkdir($fileDir, $dirPermissions, true);
  209. }
  210. if (isset($value['error']) && $value['error'] == 0) {
  211. //Crop the image to adjust 16:9 ratio
  212. $crop = new Image($value['tmp_name']);
  213. $crop->crop($params['extra_'.$field_variable.'_crop_result']);
  214. $imageExtraField = new Image($value['tmp_name']);
  215. $imageExtraField->resize(400);
  216. $imageExtraField->send_image($fileDir.$fileName, -1, 'png');
  217. $newParams = array(
  218. 'item_id' => $params['item_id'],
  219. 'field_id' => $extraFieldInfo['id'],
  220. 'value' => $fileDirStored.$fileName,
  221. 'comment' => $comment
  222. );
  223. self::save($newParams);
  224. }
  225. break;
  226. case ExtraField::FIELD_TYPE_FILE:
  227. switch ($this->type) {
  228. case 'course':
  229. $fileDir = api_get_path(SYS_UPLOAD_PATH).'courses/';
  230. $fileDirStored = "courses/";
  231. break;
  232. case 'session':
  233. $fileDir = api_get_path(SYS_UPLOAD_PATH).'sessions/';
  234. $fileDirStored = "sessions/";
  235. break;
  236. case 'user':
  237. $fileDir = UserManager::getUserPathById($params['item_id'], 'system');
  238. $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last');
  239. break;
  240. case 'work':
  241. $fileDir = api_get_path(SYS_UPLOAD_PATH).'work/';
  242. $fileDirStored = "work/";
  243. break;
  244. }
  245. $cleanedName = api_replace_dangerous_char($value['name']);
  246. $fileName = ExtraField::FIELD_TYPE_FILE."_{$params['item_id']}_$cleanedName";
  247. if (!file_exists($fileDir)) {
  248. mkdir($fileDir, $dirPermissions, true);
  249. }
  250. if (isset($value['error']) && $value['error'] == 0) {
  251. moveUploadedFile($value, $fileDir.$fileName);
  252. $new_params = array(
  253. 'item_id' => $params['item_id'],
  254. 'field_id' => $extraFieldInfo['id'],
  255. 'value' => $fileDirStored.$fileName
  256. );
  257. if ($this->type !== 'session' && $this->type !== 'course') {
  258. $new_params['comment'] = $comment;
  259. }
  260. self::save($new_params);
  261. }
  262. break;
  263. case ExtraField::FIELD_TYPE_CHECKBOX:
  264. $fieldToSave = 0;
  265. if (is_array($value)) {
  266. if (isset($value['extra_'.$field_variable])) {
  267. $fieldToSave = 1;
  268. }
  269. }
  270. $newParams = array(
  271. 'item_id' => $params['item_id'],
  272. 'field_id' => $extraFieldInfo['id'],
  273. 'value' => $fieldToSave,
  274. 'comment' => $comment
  275. );
  276. self::save($newParams);
  277. break;
  278. default:
  279. $newParams = array(
  280. 'item_id' => $params['item_id'],
  281. 'field_id' => $extraFieldInfo['id'],
  282. 'value' => $value,
  283. 'comment' => $comment
  284. );
  285. self::save($newParams, $showQuery);
  286. }
  287. }
  288. }
  289. /**
  290. * Save values in the *_field_values table
  291. * @param array $params Structured array with the values to save
  292. * @param boolean $showQuery Whether to show the insert query (passed to the parent save() method)
  293. * @return mixed The result sent from the parent method
  294. * @assert (array()) === false
  295. */
  296. public function save($params, $showQuery = false)
  297. {
  298. $extra_field = $this->getExtraField();
  299. // Setting value to insert.
  300. $value = $params['value'];
  301. $value_to_insert = null;
  302. if (is_array($value)) {
  303. $value_to_insert = implode(';', $value);
  304. } else {
  305. $value_to_insert = $value;
  306. }
  307. $params['value'] = $value_to_insert;
  308. // If field id exists
  309. if (isset($params['field_id'])) {
  310. $extraFieldInfo = $extra_field->get($params['field_id']);
  311. } else {
  312. // Try the variable
  313. $extraFieldInfo = $extra_field->get_handler_field_info_by_field_variable(
  314. $params['variable']
  315. );
  316. $params['field_id'] = $extraFieldInfo['id'];
  317. }
  318. if ($extraFieldInfo) {
  319. switch ($extraFieldInfo['field_type']) {
  320. case ExtraField::FIELD_TYPE_RADIO:
  321. case ExtraField::FIELD_TYPE_SELECT:
  322. break;
  323. case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
  324. //$field_options = $session_field_option->get_field_options_by_field($params['field_id']);
  325. //$params['field_value'] = split(';', $value_to_insert);
  326. /*
  327. if ($field_options) {
  328. $check = false;
  329. foreach ($field_options as $option) {
  330. if (in_array($option['option_value'], $values)) {
  331. $check = true;
  332. break;
  333. }
  334. }
  335. if (!$check) {
  336. return false; //option value not found
  337. }
  338. } else {
  339. return false; //enumerated type but no option found
  340. }*/
  341. break;
  342. case ExtraField::FIELD_TYPE_TEXT:
  343. case ExtraField::FIELD_TYPE_TEXTAREA:
  344. break;
  345. case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
  346. //no break
  347. case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  348. if (is_array($value)) {
  349. if (isset($value['extra_'.$extraFieldInfo['variable']]) &&
  350. isset($value['extra_'.$extraFieldInfo['variable'].'_second'])
  351. ) {
  352. $value_to_insert = $value['extra_'.$extraFieldInfo['variable']].'::'.$value['extra_'.$extraFieldInfo['variable'].'_second'];
  353. } else {
  354. $value_to_insert = null;
  355. }
  356. }
  357. break;
  358. default:
  359. break;
  360. }
  361. if ($extraFieldInfo['field_type'] == ExtraField::FIELD_TYPE_TAG) {
  362. $field_values = self::getAllValuesByItemAndFieldAndValue(
  363. $params['item_id'],
  364. $params['field_id'],
  365. $value
  366. );
  367. } else {
  368. $field_values = self::get_values_by_handler_and_field_id(
  369. $params['item_id'],
  370. $params['field_id']
  371. );
  372. }
  373. $params['value'] = $value_to_insert;
  374. //$params['author_id'] = api_get_user_id();
  375. // Insert
  376. if (empty($field_values)) {
  377. /* Enable this when field_loggeable is introduced as a table field (2.0)
  378. if ($extraFieldInfo['field_loggeable'] == 1) {
  379. */
  380. if (false) {
  381. global $app;
  382. switch ($this->type) {
  383. case 'question':
  384. $extraFieldValue = new ChamiloLMS\Entity\QuestionFieldValues();
  385. $extraFieldValue->setUserId(api_get_user_id());
  386. $extraFieldValue->setQuestionId($params[$this->handler_id]);
  387. break;
  388. case 'course':
  389. $extraFieldValue = new ChamiloLMS\Entity\CourseFieldValues();
  390. $extraFieldValue->setUserId(api_get_user_id());
  391. $extraFieldValue->setQuestionId($params[$this->handler_id]);
  392. break;
  393. case 'user':
  394. $extraFieldValue = new ChamiloLMS\Entity\UserFieldValues();
  395. $extraFieldValue->setUserId($params[$this->handler_id]);
  396. $extraFieldValue->setAuthorId(api_get_user_id());
  397. break;
  398. case 'session':
  399. $extraFieldValue = new ChamiloLMS\Entity\SessionFieldValues();
  400. $extraFieldValue->setUserId(api_get_user_id());
  401. $extraFieldValue->setSessionId($params[$this->handler_id]);
  402. break;
  403. }
  404. if (isset($extraFieldValue)) {
  405. if (!empty($params['value'])) {
  406. $extraFieldValue->setComment($params['comment']);
  407. $extraFieldValue->setFieldValue($params['value']);
  408. $extraFieldValue->setFieldId($params['field_id']);
  409. $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
  410. $app['orm.ems']['db_write']->persist($extraFieldValue);
  411. $app['orm.ems']['db_write']->flush();
  412. }
  413. }
  414. } else {
  415. if ($extraFieldInfo['field_type'] == ExtraField::FIELD_TYPE_TAG) {
  416. $option = new ExtraFieldOption($this->type);
  417. $optionExists = $option->get($params['value']);
  418. if (empty($optionExists)) {
  419. $optionParams = array(
  420. 'field_id' => $params['field_id'],
  421. 'option_value' => $params['value']
  422. );
  423. $optionId = $option->saveOptions($optionParams);
  424. } else {
  425. $optionId = $optionExists['id'];
  426. }
  427. $params['value'] = $optionId;
  428. if ($optionId) {
  429. return parent::save($params, $showQuery);
  430. }
  431. } else {
  432. return parent::save($params, $showQuery);
  433. }
  434. }
  435. } else {
  436. // Update
  437. /* Enable this when field_loggeable is introduced as a table field (2.0)
  438. if ($extraFieldInfo['field_loggeable'] == 1) {
  439. */
  440. if (false) {
  441. global $app;
  442. switch ($this->type) {
  443. case 'question':
  444. $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\Entity\QuestionFieldValues')->find($field_values['id']);
  445. $extraFieldValue->setUserId(api_get_user_id());
  446. $extraFieldValue->setQuestionId($params[$this->handler_id]);
  447. break;
  448. case 'course':
  449. $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\Entity\CourseFieldValues')->find($field_values['id']);
  450. $extraFieldValue->setUserId(api_get_user_id());
  451. $extraFieldValue->setCourseCode($params[$this->handler_id]);
  452. break;
  453. case 'user':
  454. $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\Entity\UserFieldValues')->find($field_values['id']);
  455. $extraFieldValue->setUserId(api_get_user_id());
  456. $extraFieldValue->setAuthorId(api_get_user_id());
  457. break;
  458. case 'session':
  459. $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\Entity\SessionFieldValues')->find($field_values['id']);
  460. $extraFieldValue->setUserId(api_get_user_id());
  461. $extraFieldValue->setSessionId($params[$this->handler_id]);
  462. break;
  463. }
  464. if (isset($extraFieldValue)) {
  465. if (!empty($params['value'])) {
  466. /*
  467. * If the field value is similar to the previous value then the comment will be the same
  468. in order to no save in the log an empty record
  469. */
  470. if ($extraFieldValue->getFieldValue() == $params['value']) {
  471. if (empty($params['comment'])) {
  472. $params['comment'] = $extraFieldValue->getComment();
  473. }
  474. }
  475. $extraFieldValue->setComment($params['comment']);
  476. $extraFieldValue->setFieldValue($params['value']);
  477. $extraFieldValue->setFieldId($params['field_id']);
  478. $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
  479. $app['orm.ems']['db_write']->persist($extraFieldValue);
  480. $app['orm.ems']['db_write']->flush();
  481. }
  482. }
  483. } else {
  484. $params['id'] = $field_values['id'];
  485. return parent::update($params, $showQuery);
  486. }
  487. }
  488. }
  489. }
  490. /**
  491. * Returns the value of the given extra field on the given resource
  492. * @param int $item_id Item ID (It could be a session_id, course_id or user_id)
  493. * @param int $field_id Field ID (the ID from the *_field table)
  494. * @param bool $transform Whether to transform the result to a human readable strings
  495. * @return mixed A structured array with the field_id and field_value, or false on error
  496. * @assert (-1,-1) === false
  497. */
  498. public function get_values_by_handler_and_field_id($item_id, $field_id, $transform = false)
  499. {
  500. $field_id = intval($field_id);
  501. $item_id = Database::escape_string($item_id);
  502. $sql = "SELECT s.*, field_type FROM {$this->table} s
  503. INNER JOIN {$this->table_handler_field} sf ON (s.field_id = sf.id)
  504. WHERE
  505. item_id = '$item_id' AND
  506. field_id = '".$field_id."' AND
  507. sf.extra_field_type = ".$this->getExtraField()->getExtraFieldType()."
  508. ORDER BY id";
  509. $result = Database::query($sql);
  510. if (Database::num_rows($result)) {
  511. $result = Database::fetch_array($result, 'ASSOC');
  512. if ($transform) {
  513. if (!empty($result['value'])) {
  514. switch ($result['field_type']) {
  515. case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
  516. $field_option = new ExtraFieldOption($this->type);
  517. $options = explode('::', $result['value']);
  518. // only available for PHP 5.4 :( $result['field_value'] = $field_option->get($options[0])['id'].' -> ';
  519. $result = $field_option->get($options[0]);
  520. $result_second = $field_option->get($options[1]);
  521. if (!empty($result)) {
  522. $result['value'] = $result['display_text'].' -> ';
  523. $result['value'] .= $result_second['display_text'];
  524. }
  525. break;
  526. case ExtraField::FIELD_TYPE_SELECT:
  527. $field_option = new ExtraFieldOption($this->type);
  528. $extra_field_option_result = $field_option->get_field_option_by_field_and_option(
  529. $result['field_id'],
  530. $result['value']
  531. );
  532. if (isset($extra_field_option_result[0])) {
  533. $result['value'] = $extra_field_option_result[0]['display_text'];
  534. }
  535. break;
  536. case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  537. $options = explode('::', $result['value']);
  538. $field_option = new ExtraFieldOption($this->type);
  539. $result = $field_option->get($options[0]);
  540. if (!empty($result)) {
  541. $result['value'] = $result['display_text']
  542. .'&rarr;'
  543. .$options[1];
  544. }
  545. break;
  546. case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
  547. $optionIds = explode(';', $result['value']);
  548. $optionValues = [];
  549. foreach ($optionIds as $optionId) {
  550. $objEfOption = new ExtraFieldOption('user');
  551. $optionInfo = $objEfOption->get($optionId);
  552. $optionValues[] = $optionInfo['display_text'];
  553. }
  554. $result['value'] = implode(' / ', $optionValues);
  555. break;
  556. }
  557. }
  558. }
  559. return $result;
  560. } else {
  561. return false;
  562. }
  563. }
  564. /**
  565. * @param string $tag
  566. * @param int $field_id
  567. * @param int $limit
  568. *
  569. * @return array
  570. */
  571. public function searchValuesByField($tag, $field_id, $limit = 10)
  572. {
  573. $field_id = intval($field_id);
  574. $limit = intval($limit);
  575. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  576. $tag = Database::escape_string($tag);
  577. $sql = "SELECT DISTINCT s.value, s.field_id
  578. FROM {$this->table} s
  579. INNER JOIN {$this->table_handler_field} sf
  580. ON (s.field_id = sf.id)
  581. WHERE
  582. field_id = '".$field_id."' AND
  583. value LIKE '%$tag%' AND
  584. sf.extra_field_type = ".$extraFieldType."
  585. ORDER BY value
  586. LIMIT 0, $limit
  587. ";
  588. $result = Database::query($sql);
  589. $values = array();
  590. if (Database::num_rows($result)) {
  591. $values = Database::store_result($result, 'ASSOC');
  592. }
  593. return $values;
  594. }
  595. /**
  596. * Gets a structured array of the original item and its extra values, using
  597. * a specific original item and a field name (like "branch", or "birthdate")
  598. * @param int $item_id Item ID from the original table
  599. * @param string $field_variable The name of the field we are looking for
  600. * @param bool $transform
  601. * @param bool $filterByVisibility
  602. * @param int $visibility
  603. *
  604. * @return mixed Array of results, or false on error or not found
  605. * @assert (-1,'') === false
  606. */
  607. public function get_values_by_handler_and_field_variable(
  608. $item_id,
  609. $field_variable,
  610. $transform = false,
  611. $filterByVisibility = false,
  612. $visibility = 0
  613. ) {
  614. $item_id = intval($item_id);
  615. $field_variable = Database::escape_string($field_variable);
  616. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  617. $sql = "SELECT s.*, field_type
  618. FROM {$this->table} s
  619. INNER JOIN {$this->table_handler_field} sf
  620. ON (s.field_id = sf.id)
  621. WHERE
  622. item_id = '$item_id' AND
  623. variable = '".$field_variable."' AND
  624. sf.extra_field_type = $extraFieldType
  625. ";
  626. if ($filterByVisibility) {
  627. $visibility = intval($visibility);
  628. $sql .= " AND visible_to_self = $visibility ";
  629. }
  630. $sql .= " ORDER BY id";
  631. $result = Database::query($sql);
  632. if (Database::num_rows($result)) {
  633. $result = Database::fetch_array($result, 'ASSOC');
  634. if ($transform) {
  635. if ($result['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  636. if (!empty($result['value'])) {
  637. $field_option = new ExtraFieldOption($this->type);
  638. $options = explode('::', $result['value']);
  639. $result = $field_option->get($options[0]);
  640. $result_second = $field_option->get($options[1]);
  641. if (!empty($result)) {
  642. $result['value'] = $result['display_text'].' -> ';
  643. $result['value'] .= $result_second['display_text'];
  644. }
  645. }
  646. }
  647. if ($result['field_type'] == ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD) {
  648. if (!empty($result['value'])) {
  649. $options = explode('::', $result['value']);
  650. $field_option = new ExtraFieldOption($this->type);
  651. $result = $field_option->get($options[0]);
  652. if (!empty($result)) {
  653. $result['value'] = $result['display_text']
  654. .'&rarr;'
  655. .$options[1];
  656. }
  657. }
  658. }
  659. if ($result['field_type'] == ExtraField::FIELD_TYPE_TRIPLE_SELECT) {
  660. if (!empty($result['value'])) {
  661. $optionIds = explode(';', $result['value']);
  662. $optionValues = [];
  663. foreach ($optionIds as $optionId) {
  664. $objEfOption = new ExtraFieldOption('user');
  665. $optionInfo = $objEfOption->get($optionId);
  666. $optionValues[] = $optionInfo['display_text'];
  667. }
  668. $result['value'] = implode(' / ', $optionValues);
  669. }
  670. }
  671. }
  672. return $result;
  673. } else {
  674. return false;
  675. }
  676. }
  677. /**
  678. * Gets the ID from the item (course, session, etc) for which
  679. * the given field is defined with the given value
  680. * @param string $field_variable Field (type of data) we want to check
  681. * @param string $field_value Data we are looking for in the given field
  682. * @param bool $transform Whether to transform the result to a human readable strings
  683. * @param bool $last Whether to return the last element or simply the first one we get
  684. * @return mixed Give the ID if found, or false on failure or not found
  685. * @assert (-1,-1) === false
  686. */
  687. public function get_item_id_from_field_variable_and_field_value(
  688. $field_variable,
  689. $field_value,
  690. $transform = false,
  691. $last = false,
  692. $all = false
  693. ) {
  694. $field_value = Database::escape_string($field_value);
  695. $field_variable = Database::escape_string($field_variable);
  696. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  697. $sql = "SELECT item_id FROM {$this->table} s
  698. INNER JOIN {$this->table_handler_field} sf
  699. ON (s.field_id = sf.id)
  700. WHERE
  701. value = '$field_value' AND
  702. variable = '".$field_variable."' AND
  703. sf.extra_field_type = $extraFieldType
  704. ORDER BY item_id
  705. ";
  706. if ($last) {
  707. // If we want the last element instead of the first
  708. // This is useful in special cases where there might
  709. // (erroneously) be more than one row for an item
  710. $sql .= ' DESC';
  711. }
  712. $result = Database::query($sql);
  713. if ($result !== false && Database::num_rows($result)) {
  714. if ($all) {
  715. $result = Database::store_result($result, 'ASSOC');
  716. } else {
  717. $result = Database::fetch_array($result, 'ASSOC');
  718. }
  719. return $result;
  720. } else {
  721. return false;
  722. }
  723. }
  724. /**
  725. * Get all the values stored for one specific field
  726. * @param int $fieldId
  727. *
  728. * @return array|bool
  729. */
  730. public function getValuesByFieldId($fieldId)
  731. {
  732. $fieldId = intval($fieldId);
  733. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  734. $sql = "SELECT s.* FROM {$this->table} s
  735. INNER JOIN {$this->table_handler_field} sf
  736. ON (s.field_id = sf.id)
  737. WHERE
  738. field_id = '".$fieldId."' AND
  739. sf.extra_field_type = $extraFieldType
  740. ORDER BY s.value";
  741. $result = Database::query($sql);
  742. if (Database::num_rows($result)) {
  743. return Database::store_result($result, 'ASSOC');
  744. }
  745. return false;
  746. }
  747. /**
  748. * @param int $itemId
  749. * @param int $fieldId
  750. * @return array
  751. */
  752. public function getAllValuesByItemAndField($itemId, $fieldId)
  753. {
  754. $fieldId = intval($fieldId);
  755. $itemId = intval($itemId);
  756. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  757. $sql = "SELECT s.* FROM {$this->table} s
  758. INNER JOIN {$this->table_handler_field} sf
  759. ON (s.field_id = sf.id)
  760. WHERE
  761. field_id = '".$fieldId."' AND
  762. item_id = '$itemId' AND
  763. sf.extra_field_type = $extraFieldType
  764. ORDER BY s.value";
  765. $result = Database::query($sql);
  766. if (Database::num_rows($result)) {
  767. return Database::store_result($result, 'ASSOC');
  768. }
  769. return false;
  770. }
  771. /**
  772. * @param int $itemId
  773. *
  774. * @return array
  775. */
  776. public function getAllValuesByItem($itemId)
  777. {
  778. $itemId = intval($itemId);
  779. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  780. $sql = "SELECT s.value, sf.variable, sf.field_type, sf.id
  781. FROM {$this->table} s
  782. INNER JOIN {$this->table_handler_field} sf
  783. ON (s.field_id = sf.id)
  784. WHERE
  785. item_id = '$itemId' AND
  786. sf.extra_field_type = $extraFieldType
  787. ORDER BY s.value";
  788. $result = Database::query($sql);
  789. if (Database::num_rows($result)) {
  790. return Database::store_result($result, 'ASSOC');
  791. }
  792. return false;
  793. }
  794. /**
  795. * @param int $itemId
  796. * @param int $fieldId
  797. * @param string $fieldValue
  798. *
  799. * @return array|bool
  800. */
  801. public function getAllValuesByItemAndFieldAndValue($itemId, $fieldId, $fieldValue)
  802. {
  803. $fieldId = intval($fieldId);
  804. $itemId = intval($itemId);
  805. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  806. $fieldValue = Database::escape_string($fieldValue);
  807. $sql = "SELECT s.* FROM {$this->table} s
  808. INNER JOIN {$this->table_handler_field} sf
  809. ON (s.field_id = sf.id)
  810. WHERE
  811. field_id = '$fieldId' AND
  812. item_id = '$itemId' AND
  813. value = '$fieldValue' AND
  814. sf.extra_field_type = $extraFieldType
  815. ORDER BY value";
  816. $result = Database::query($sql);
  817. if (Database::num_rows($result)) {
  818. return Database::store_result($result, 'ASSOC');
  819. }
  820. return false;
  821. }
  822. /**
  823. * Deletes all the values related to a specific field ID
  824. * @param int $field_id
  825. *
  826. * @return void
  827. * @assert ('a') == null
  828. */
  829. public function delete_all_values_by_field_id($field_id)
  830. {
  831. $field_id = intval($field_id);
  832. $sql = "DELETE FROM {$this->table}
  833. WHERE
  834. field_id = $field_id ";
  835. Database::query($sql);
  836. }
  837. /**
  838. * Deletes values of a specific field for a specific item
  839. * @param int $item_id (session id, course id, etc)
  840. * @param int $field_id
  841. * @return void
  842. * @assert (-1,-1) == null
  843. */
  844. public function delete_values_by_handler_and_field_id($item_id, $field_id)
  845. {
  846. $field_id = intval($field_id);
  847. $item_id = intval($item_id);
  848. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  849. $sql = "DELETE FROM {$this->table}
  850. WHERE
  851. item_id = '$item_id' AND
  852. field_id = '$field_id'
  853. ";
  854. Database::query($sql);
  855. }
  856. /**
  857. * Deletes all values from an item
  858. * @param int $itemId (session id, course id, etc)
  859. * @assert (-1,-1) == null
  860. */
  861. public function deleteValuesByItem($itemId)
  862. {
  863. $itemId = intval($itemId);
  864. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  865. $sql = "DELETE FROM {$this->table}
  866. WHERE
  867. item_id = '$itemId' AND
  868. field_id IN (
  869. SELECT id FROM {$this->table_handler_field}
  870. WHERE extra_field_type = ".$extraFieldType."
  871. )
  872. ";
  873. Database::query($sql);
  874. }
  875. /**
  876. * @param int $itemId
  877. * @param int $fieldId
  878. * @param int $fieldValue
  879. */
  880. public function deleteValuesByHandlerAndFieldAndValue($itemId, $fieldId, $fieldValue)
  881. {
  882. $itemId = intval($itemId);
  883. $fieldId = intval($fieldId);
  884. $fieldValue = Database::escape_string($fieldValue);
  885. $sql = "DELETE FROM {$this->table}
  886. WHERE
  887. item_id = '$itemId' AND
  888. field_id = '$fieldId' AND
  889. value = '$fieldValue'
  890. ";
  891. Database::query($sql);
  892. }
  893. /**
  894. * Not yet implemented - Compares the field values of two items
  895. * @param int $item_id Item 1
  896. * @param int $item_to_compare Item 2
  897. * @todo
  898. * @return mixed Differential array generated from the comparison
  899. */
  900. public function compareItemValues($item_id, $item_to_compare)
  901. {
  902. }
  903. /**
  904. * Get all values for an item
  905. * @param int $itemId The item ID
  906. * @param boolean $visibleToSelf Get the visible extra field only
  907. * @param boolean $visibleToOthers
  908. *
  909. * @return array
  910. */
  911. public function getAllValuesForAnItem($itemId, $visibleToSelf = null, $visibleToOthers = null)
  912. {
  913. $em = Database::getManager();
  914. /** @var \Doctrine\DBAL\Query\QueryBuilder $qb */
  915. $qb = $em->createQueryBuilder();
  916. $qb = $qb->select('fv')
  917. ->from('ChamiloCoreBundle:ExtraFieldValues', 'fv')
  918. ->join('fv.field', 'f')
  919. ->where(
  920. $qb->expr()->eq('fv.itemId', ':item')
  921. );
  922. if (is_bool($visibleToSelf)) {
  923. $qb
  924. ->andWhere($qb->expr()->eq('f.visibleToSelf', ':visibleToSelf'))
  925. ->setParameter('visibleToSelf', $visibleToSelf);
  926. }
  927. if (is_bool($visibleToOthers)) {
  928. $qb
  929. ->andWhere($qb->expr()->eq('f.visibleToOthers', ':visibleToOthers'))
  930. ->setParameter('visibleToOthers', $visibleToOthers);
  931. }
  932. $fieldValues = $qb
  933. ->setParameter('item', $itemId)
  934. ->getQuery()
  935. ->getResult();
  936. $fieldOptionsRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldOptions');
  937. $valueList = [];
  938. /** @var ExtraFieldValues $fieldValue */
  939. foreach ($fieldValues as $fieldValue) {
  940. $item = [
  941. 'value' => $fieldValue
  942. ];
  943. switch ($fieldValue->getField()->getFieldType()) {
  944. case ExtraField::FIELD_TYPE_SELECT:
  945. $item['option'] = $fieldOptionsRepo->findOneBy([
  946. 'field' => $fieldValue->getField(),
  947. 'value' => $fieldValue->getValue()
  948. ]);
  949. break;
  950. }
  951. $valueList[] = $item;
  952. }
  953. return $valueList;
  954. }
  955. }