extra_field_value.lib.php 41 KB

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