extra_field_value.lib.php 38 KB

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