extra_field_value.lib.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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 = $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 $filterByVisibility
  559. * @param int $visibility
  560. *
  561. * @return mixed Array of results, or false on error or not found
  562. * @assert (-1,'') === false
  563. */
  564. public function get_values_by_handler_and_field_variable(
  565. $item_id,
  566. $field_variable,
  567. $transform = false,
  568. $filterByVisibility = false,
  569. $visibility = 0
  570. ) {
  571. $item_id = intval($item_id);
  572. $field_variable = Database::escape_string($field_variable);
  573. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  574. $sql = "SELECT s.*, field_type
  575. FROM {$this->table} s
  576. INNER JOIN {$this->table_handler_field} sf
  577. ON (s.field_id = sf.id)
  578. WHERE
  579. item_id = '$item_id' AND
  580. variable = '".$field_variable."' AND
  581. sf.extra_field_type = $extraFieldType
  582. ";
  583. if ($filterByVisibility) {
  584. $visibility = intval($visibility);
  585. $sql .= " AND visible_to_self = $visibility ";
  586. }
  587. $sql .= " ORDER BY id";
  588. $result = Database::query($sql);
  589. if (Database::num_rows($result)) {
  590. $result = Database::fetch_array($result, 'ASSOC');
  591. if ($transform) {
  592. if ($result['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  593. if (!empty($result['value'])) {
  594. $field_option = new ExtraFieldOption($this->type);
  595. $options = explode('::', $result['value']);
  596. $result = $field_option->get($options[0]);
  597. $result_second = $field_option->get($options[1]);
  598. if (!empty($result)) {
  599. $result['value'] = $result['display_text'].' -> ';
  600. $result['value'] .= $result_second['display_text'];
  601. }
  602. }
  603. }
  604. }
  605. return $result;
  606. } else {
  607. return false;
  608. }
  609. }
  610. /**
  611. * Gets the ID from the item (course, session, etc) for which
  612. * the given field is defined with the given value
  613. * @param string $field_variable Field (type of data) we want to check
  614. * @param string $field_value Data we are looking for in the given field
  615. * @param bool $transform Whether to transform the result to a human readable strings
  616. * @param bool $last Whether to return the last element or simply the first one we get
  617. * @return mixed Give the ID if found, or false on failure or not found
  618. * @assert (-1,-1) === false
  619. */
  620. public function get_item_id_from_field_variable_and_field_value(
  621. $field_variable,
  622. $field_value,
  623. $transform = false,
  624. $last = false,
  625. $all = false
  626. ) {
  627. $field_value = Database::escape_string($field_value);
  628. $field_variable = Database::escape_string($field_variable);
  629. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  630. $sql = "SELECT item_id FROM {$this->table} s
  631. INNER JOIN {$this->table_handler_field} sf
  632. ON (s.field_id = sf.id)
  633. WHERE
  634. value = '$field_value' AND
  635. variable = '".$field_variable."' AND
  636. sf.extra_field_type = $extraFieldType
  637. ORDER BY item_id
  638. ";
  639. if ($last) {
  640. // If we want the last element instead of the first
  641. // This is useful in special cases where there might
  642. // (erroneously) be more than one row for an item
  643. $sql .= ' DESC';
  644. }
  645. $result = Database::query($sql);
  646. if ($result !== false && Database::num_rows($result)) {
  647. if ($all) {
  648. $result = Database::store_result($result, 'ASSOC');
  649. } else {
  650. $result = Database::fetch_array($result, 'ASSOC');
  651. }
  652. return $result;
  653. } else {
  654. return false;
  655. }
  656. }
  657. /**
  658. * Get all the values stored for one specific field
  659. * @param int $fieldId
  660. *
  661. * @return array|bool
  662. */
  663. public function getValuesByFieldId($fieldId)
  664. {
  665. $fieldId = intval($fieldId);
  666. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  667. $sql = "SELECT s.* FROM {$this->table} s
  668. INNER JOIN {$this->table_handler_field} sf
  669. ON (s.field_id = sf.id)
  670. WHERE
  671. field_id = '".$fieldId."' AND
  672. sf.extra_field_type = $extraFieldType
  673. ORDER BY s.value";
  674. $result = Database::query($sql);
  675. if (Database::num_rows($result)) {
  676. return Database::store_result($result, 'ASSOC');
  677. }
  678. return false;
  679. }
  680. /**
  681. * @param int $itemId
  682. * @param int $fieldId
  683. * @return array
  684. */
  685. public function getAllValuesByItemAndField($itemId, $fieldId)
  686. {
  687. $fieldId = intval($fieldId);
  688. $itemId = intval($itemId);
  689. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  690. $sql = "SELECT s.* FROM {$this->table} s
  691. INNER JOIN {$this->table_handler_field} sf
  692. ON (s.field_id = sf.id)
  693. WHERE
  694. field_id = '".$fieldId."' AND
  695. item_id = '$itemId' AND
  696. sf.extra_field_type = $extraFieldType
  697. ORDER BY s.value";
  698. $result = Database::query($sql);
  699. if (Database::num_rows($result)) {
  700. return Database::store_result($result, 'ASSOC');
  701. }
  702. return false;
  703. }
  704. /**
  705. * @param int $itemId
  706. *
  707. * @return array
  708. */
  709. public function getAllValuesByItem($itemId)
  710. {
  711. $itemId = intval($itemId);
  712. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  713. $sql = "SELECT s.value, sf.variable FROM {$this->table} s
  714. INNER JOIN {$this->table_handler_field} sf
  715. ON (s.field_id = sf.id)
  716. WHERE
  717. item_id = '$itemId' AND
  718. sf.extra_field_type = $extraFieldType
  719. ORDER BY s.value";
  720. $result = Database::query($sql);
  721. if (Database::num_rows($result)) {
  722. return Database::store_result($result, 'ASSOC');
  723. }
  724. return false;
  725. }
  726. /**
  727. * @param int $itemId
  728. * @param int $fieldId
  729. * @param string $fieldValue
  730. *
  731. * @return array|bool
  732. */
  733. public function getAllValuesByItemAndFieldAndValue($itemId, $fieldId, $fieldValue)
  734. {
  735. $fieldId = intval($fieldId);
  736. $itemId = intval($itemId);
  737. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  738. $fieldValue = Database::escape_string($fieldValue);
  739. $sql = "SELECT s.* FROM {$this->table} s
  740. INNER JOIN {$this->table_handler_field} sf
  741. ON (s.field_id = sf.id)
  742. WHERE
  743. field_id = '$fieldId' AND
  744. item_id = '$itemId' AND
  745. value = '$fieldValue' AND
  746. sf.extra_field_type = $extraFieldType
  747. ORDER BY value";
  748. $result = Database::query($sql);
  749. if (Database::num_rows($result)) {
  750. return Database::store_result($result, 'ASSOC');
  751. }
  752. return false;
  753. }
  754. /**
  755. * Deletes all the values related to a specific field ID
  756. * @param int $field_id
  757. *
  758. * @return void
  759. * @assert ('a') == null
  760. */
  761. public function delete_all_values_by_field_id($field_id)
  762. {
  763. $field_id = intval($field_id);
  764. $sql = "DELETE FROM {$this->table}
  765. WHERE
  766. field_id = $field_id ";
  767. Database::query($sql);
  768. }
  769. /**
  770. * Deletes values of a specific field for a specific item
  771. * @param int $item_id (session id, course id, etc)
  772. * @param int $field_id
  773. * @return void
  774. * @assert (-1,-1) == null
  775. */
  776. public function delete_values_by_handler_and_field_id($item_id, $field_id)
  777. {
  778. $field_id = intval($field_id);
  779. $item_id = intval($item_id);
  780. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  781. $sql = "DELETE FROM {$this->table}
  782. WHERE
  783. item_id = '$item_id' AND
  784. field_id = '$field_id' AND
  785. extra_field_type = $extraFieldType
  786. ";
  787. Database::query($sql);
  788. }
  789. /**
  790. * Deletes all values from an item
  791. * @param int $itemId (session id, course id, etc)
  792. * @assert (-1,-1) == null
  793. */
  794. public function deleteValuesByItem($itemId)
  795. {
  796. $itemId = intval($itemId);
  797. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  798. $sql = "DELETE FROM {$this->table}
  799. WHERE
  800. item_id = '$itemId' AND
  801. field_id IN (
  802. SELECT id FROM {$this->table_handler_field}
  803. WHERE extra_field_type = ".$extraFieldType."
  804. )
  805. ";
  806. Database::query($sql);
  807. }
  808. /**
  809. * @param int $itemId
  810. * @param int $fieldId
  811. * @param int $fieldValue
  812. */
  813. public function deleteValuesByHandlerAndFieldAndValue($itemId, $fieldId, $fieldValue)
  814. {
  815. $itemId = intval($itemId);
  816. $fieldId = intval($fieldId);
  817. $fieldValue = Database::escape_string($fieldValue);
  818. $sql = "DELETE FROM {$this->table}
  819. WHERE
  820. item_id = '$itemId' AND
  821. field_id = '$fieldId' AND
  822. value = '$fieldValue'
  823. ";
  824. Database::query($sql);
  825. }
  826. /**
  827. * Not yet implemented - Compares the field values of two items
  828. * @param int $item_id Item 1
  829. * @param int $item_to_compare Item 2
  830. * @todo
  831. * @return mixed Differential array generated from the comparison
  832. */
  833. public function compareItemValues($item_id, $item_to_compare)
  834. {
  835. }
  836. /**
  837. * Get all values for an item
  838. * @param int $itemId The item ID
  839. * @param boolean $visibleToSelf Get the visible extra field only
  840. * @param boolean $visibleToOthers
  841. *
  842. * @return array
  843. */
  844. public function getAllValuesForAnItem($itemId, $visibleToSelf = null, $visibleToOthers = null)
  845. {
  846. $em = Database::getManager();
  847. /** @var \Doctrine\DBAL\Query\QueryBuilder $qb */
  848. $qb = $em->createQueryBuilder();
  849. $qb = $qb->select('fv')
  850. ->from('ChamiloCoreBundle:ExtraFieldValues', 'fv')
  851. ->join('fv.field', 'f')
  852. ->where(
  853. $qb->expr()->eq('fv.itemId', ':item')
  854. );
  855. if (is_bool($visibleToSelf)) {
  856. $qb
  857. ->andWhere($qb->expr()->eq('f.visibleToSelf', ':visibleToSelf'))
  858. ->setParameter('visibleToSelf', $visibleToSelf);
  859. }
  860. if (is_bool($visibleToOthers)) {
  861. $qb
  862. ->andWhere($qb->expr()->eq('f.visibleToOthers', ':visibleToOthers'))
  863. ->setParameter('visibleToOthers', $visibleToOthers);
  864. }
  865. $fieldValues = $qb
  866. ->setParameter('item', $itemId)
  867. ->getQuery()
  868. ->getResult();
  869. $fieldOptionsRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldOptions');
  870. $valueList = [];
  871. /** @var ExtraFieldValues $fieldValue */
  872. foreach ($fieldValues as $fieldValue) {
  873. $item = [
  874. 'value' => $fieldValue
  875. ];
  876. switch ($fieldValue->getField()->getFieldType()) {
  877. case ExtraField::FIELD_TYPE_SELECT:
  878. $item['option'] = $fieldOptionsRepo->findOneBy([
  879. 'field' => $fieldValue->getField(),
  880. 'value' => $fieldValue->getValue()
  881. ]);
  882. break;
  883. }
  884. $valueList[] = $item;
  885. }
  886. return $valueList;
  887. }
  888. }