extra_field_value.lib.php 37 KB

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