extra_field_value.lib.php 38 KB

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