Advertisement
tabvn

Untitled

Apr 14th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 24.28 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. define('DEXP_ROOT_API', 'dexp');
  5. define('DEXP_DEBUG', TRUE);
  6.  
  7. $dexp_settings = [];
  8. $dexp_settings_formatters = [];
  9.  
  10. function dexp_photos_menu() {
  11.  
  12.  
  13.   $items[DEXP_ROOT_API] = [
  14.     'title' => 'Providing Restful service root endpoint for Photos',
  15.     'page callback' => 'dexp_photos_handle_rest',
  16.     'access arguments' => ['access content'],
  17.     'file' => 'dexp_photos.pages.inc',
  18.     'type' => MENU_CALLBACK,
  19.   ];
  20.  
  21.   return $items;
  22. }
  23.  
  24.  
  25. /**
  26.  * Implement hook_permissions
  27.  *
  28.  * @return array
  29.  */
  30.  
  31. function dexp_photos_permission() {
  32.   return [
  33.     'administer albums' => [
  34.       'title' => t('Administer albums'),
  35.       'description' => t('Manage album photo'),
  36.     ],
  37.     'create album' => [
  38.       'title' => t('Create new album'),
  39.       'description' => t('Create new album'),
  40.     ],
  41.   ];
  42. }
  43.  
  44. /**
  45.  * Implements hook_field_info().
  46.  *
  47.  */
  48. function dexp_photos_field_info() {
  49.   return [
  50.     // We name our field as the associative name of the array.
  51.     'dexp_photos' => [
  52.       'label' => t('Photo Album'),
  53.       'description' => t('Photo Album'),
  54.       'default_widget' => 'dexp_photos_widget',
  55.       'default_formatter' => 'dexp_photos_formatter',
  56.     ],
  57.   ];
  58. }
  59.  
  60.  
  61. /**
  62.  * Implements hook_field_is_empty().
  63.  */
  64. function dexp_photos_field_is_empty($item, $field) {
  65.   return empty($item['data']);
  66. }
  67.  
  68. /**
  69.  * Implements hook_field_formatter_info().
  70.  */
  71. function dexp_photos_field_formatter_info() {
  72.   return [
  73.     // This formatter just displays the hex value in the color indicated.
  74.     'dexp_photos_formatter' => [
  75.       'label' => t('Photo album formatter'),
  76.       'field types' => ['dexp_photos'],
  77.     ],
  78.   ];
  79. }
  80.  
  81. /**
  82.  * Implements hook_field_formatter_view().
  83.  */
  84. function dexp_photos_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  85.  
  86.   global $dexp_settings_formatters;
  87.  
  88.   $element = [];
  89.   switch ($display['type']) {
  90.  
  91.  
  92.     case 'dexp_photos_formatter':
  93.  
  94.       $htmlId = drupal_html_id('dexp-photos-formatter');
  95.       $lib = dexp_photo_get_lib();
  96.  
  97.       foreach ($items as $delta => $item) {
  98.  
  99.         $element[$delta] = [
  100.           '#type' => 'html_tag',
  101.           '#tag' => 'div',
  102.           '#value' => $item['data'],
  103.           '#attributes' => [
  104.             'id' => $htmlId,
  105.           ],
  106.           '#attached' => [
  107.             'js' => $lib['js'],
  108.             'css' => $lib['css'],
  109.           ],
  110.         ];
  111.  
  112.  
  113.         $value = $item['data'];
  114.  
  115.         $albumIds = drupal_json_decode($value);
  116.         $albumResults = [];
  117.         $ids = [];
  118.         if (!empty($albumIds)) {
  119.  
  120.           $filter = new stdClass();
  121.           $where = new stdClass();
  122.           $where->field = 'id';
  123.           $where->value = $albumIds;
  124.           $where->operator = 'IN';
  125.           $filter->where = [$where];
  126.           $albums = dexp_photos_get_albums($filter);
  127.  
  128.           $map = [];
  129.  
  130.           if (!empty($albums)) {
  131.             foreach ($albums as $album) {
  132.               $map[$album['id']] = $album;
  133.             }
  134.           }
  135.  
  136.           foreach ($albumIds as $aid) {
  137.             if (isset($map[$aid])) {
  138.               $ids[] = $aid;
  139.               $albumResults[] = $map[$aid];
  140.             }
  141.  
  142.           }
  143.         }
  144.  
  145.         $dexp_settings_formatters[] = [
  146.           'id' => $htmlId,
  147.           'albums' => $albumResults,
  148.         ];
  149.  
  150.         drupal_add_js(['dexp_photos' => ['formatters' => $dexp_settings_formatters]], 'setting');
  151.  
  152.  
  153.       }
  154.  
  155.  
  156.       break;
  157.   }
  158.  
  159.   return $element;
  160. }
  161.  
  162. /**
  163.  * Implements hook_field_widget_info().
  164.  */
  165. function dexp_photos_field_widget_info() {
  166.   return [
  167.     'dexp_photos_widget' => [
  168.       'label' => t('Photo album widget'),
  169.       'field types' => ['dexp_photos'],
  170.     ],
  171.   ];
  172. }
  173.  
  174.  
  175. function dexp_photo_get_lib() {
  176.   $module_path = drupal_get_path('module', 'dexp_photos');
  177.   $lib = [
  178.     'js' => [
  179.       $module_path . '/static/js/runtime~main.a8a9905a.js',
  180.       $module_path . '/static/js/2.4e403482.chunk.js',
  181.       $module_path . '/static/js/main.56e35a6a.chunk.js',
  182.       $module_path . '/assets/js/main.js',
  183.     ],
  184.     'css' => [
  185.       $module_path . '/static/css/2.73e73780.chunk.css',
  186.     ],
  187.   ];
  188.  
  189.   return $lib;
  190. }
  191.  
  192. /**
  193.  * Implements hook_field_widget_form().
  194.  */
  195. function dexp_photos_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  196.  
  197.   global $dexp_settings;
  198.  
  199.   $value = isset($items[$delta]['data']) ? $items[$delta]['data'] : '';
  200.  
  201.  
  202.   $widget = $element;
  203.   $widget['#delta'] = $delta;
  204.  
  205.   $title = isset($element['#title']) ? $element['#title'] : '';
  206.  
  207.   switch ($instance['widget']['type']) {
  208.     case 'dexp_photos_widget':
  209.  
  210.       $lib = dexp_photo_get_lib();
  211.       $htmlId = drupal_html_id('dexp-photos-widget');
  212.  
  213.  
  214.       $widget += [
  215.         '#suffix' => '<div class="form-item"><label>' . $title . '</label><div id="' . $htmlId . '" class="field-dexp-photos"></div></div>',
  216.         '#attributes' => [
  217.           'class' => ['edit-field-dexp-photos-widget'],
  218.           'id' => "$htmlId-textarea",
  219.         ],
  220.         '#attached' => [
  221.           'js' => $lib['js'],
  222.           'css' => $lib['css'],
  223.         ],
  224.       ];
  225.  
  226.  
  227.       $albumIds = drupal_json_decode($value);
  228.       $albumResults = [];
  229.       $ids = [];
  230.       if (!empty($albumIds)) {
  231.  
  232.         $filter = new stdClass();
  233.         $where = new stdClass();
  234.         $where->field = 'id';
  235.         $where->value = $albumIds;
  236.         $where->operator = 'IN';
  237.         $filter->where = [$where];
  238.         $albums = dexp_photos_get_albums($filter);
  239.  
  240.         $map = [];
  241.  
  242.         if (!empty($albums)) {
  243.           foreach ($albums as $album) {
  244.             $map[$album['id']] = $album;
  245.           }
  246.         }
  247.  
  248.         foreach ($albumIds as $aid) {
  249.           if (isset($map[$aid])) {
  250.             $ids[] = $aid;
  251.             $albumResults[] = $map[$aid];
  252.           }
  253.  
  254.         }
  255.       }
  256.  
  257.  
  258.       $dexp_settings[] = [
  259.         'id' => $htmlId,
  260.         'albums' => $albumResults,
  261.       ];
  262.  
  263.  
  264.       drupal_add_js(['dexp_photos' => ['widgets' => $dexp_settings]], 'setting');
  265.  
  266.       $widget += [
  267.         '#type' => 'hidden',
  268.         '#default_value' => json_encode($ids),
  269.       ];
  270.  
  271.   }
  272.  
  273.   $element['data'] = $widget;
  274.   return $element;
  275. }
  276.  
  277.  
  278. /**
  279.  * Implements hook_field_widget_error().
  280.  */
  281. function dexp_photos_field_widget_error($element, $error, $form, &$form_state) {
  282.   switch ($error['error']) {
  283.     case 'dexp_photos_invalid':
  284.       form_error($element, $error['message']);
  285.       break;
  286.   }
  287. }
  288.  
  289. /**
  290.  * Implements hook_field_delete()
  291.  */
  292. function dexp_photos_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  293.  
  294.   if ($field['type'] == 'dexp_photos') {
  295.     foreach ($items as $delta => $item) {
  296.       $data = isset($item['data']) ? $item['data'] : NULL;
  297.       $albumIds = json_decode($data);
  298.       if (!empty($albumIds)) {
  299.         foreach ($albumIds as $albumId) {
  300.           dexp_photos_delete_album($albumId);
  301.         }
  302.       }
  303.  
  304.     }
  305.   }
  306.  
  307. }
  308.  
  309. function dexp_save_upload($form_field_name, $validators = [], $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
  310.   global $user;
  311.   static $upload_cache;
  312.  
  313.   // Return cached objects without processing since the file will have
  314.   // already been processed and the paths in _FILES will be invalid.
  315.   if (isset($upload_cache[$form_field_name])) {
  316.     return $upload_cache[$form_field_name];
  317.   }
  318.  
  319.   // Make sure there's an upload to process.
  320.   if (empty($_FILES['files']['name'])) {
  321.     return NULL;
  322.   }
  323.  
  324.   // Check for file upload errors and return FALSE if a lower level system
  325.   // error occurred. For a complete list of errors:
  326.   // See http://php.net/manual/features.file-upload.errors.php.
  327.   switch ($_FILES['files']['error']) {
  328.     case UPLOAD_ERR_INI_SIZE:
  329.     case UPLOAD_ERR_FORM_SIZE:
  330.       drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', [
  331.         '%file' => $_FILES['files']['name'],
  332.         '%maxsize' => format_size(file_upload_max_size()),
  333.       ]), 'error');
  334.       return FALSE;
  335.  
  336.     case UPLOAD_ERR_PARTIAL:
  337.     case UPLOAD_ERR_NO_FILE:
  338.       drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', ['%file' => $_FILES['files']['name']]), 'error');
  339.       return FALSE;
  340.  
  341.     case UPLOAD_ERR_OK:
  342.       // Final check that this is a valid upload, if it isn't, use the
  343.       // default error handler.
  344.       if (is_uploaded_file($_FILES['files']['tmp_name'])) {
  345.         break;
  346.       }
  347.  
  348.     // Unknown error
  349.     default:
  350.       drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', ['%file' => $_FILES['files']['name']]), 'error');
  351.       return FALSE;
  352.   }
  353.  
  354.   // Begin building file object.
  355.   $file = new stdClass();
  356.   $file->uid = $user->uid;
  357.   $file->status = 0;
  358.   $file->filename = trim(drupal_basename($_FILES['files']['name']), '.');
  359.   $file->uri = $_FILES['files']['tmp_name'];
  360.   $file->filemime = file_get_mimetype($file->filename);
  361.   $file->filesize = $_FILES['files']['size'];
  362.   $file->status = FILE_STATUS_PERMANENT;
  363.  
  364.  
  365.   $extensions = '';
  366.   if (isset($validators['file_validate_extensions'])) {
  367.     if (isset($validators['file_validate_extensions'][0])) {
  368.       // Build the list of non-munged extensions if the caller provided them.
  369.       $extensions = $validators['file_validate_extensions'][0];
  370.     }
  371.     else {
  372.       // If 'file_validate_extensions' is set and the list is empty then the
  373.       // caller wants to allow any extension. In this case we have to remove the
  374.       // validator or else it will reject all extensions.
  375.       unset($validators['file_validate_extensions']);
  376.     }
  377.   }
  378.   else {
  379.     // No validator was provided, so add one using the default list.
  380.     // Build a default non-munged safe list for file_munge_filename().
  381.     $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
  382.     $validators['file_validate_extensions'] = [];
  383.     $validators['file_validate_extensions'][0] = $extensions;
  384.   }
  385.  
  386.   if (!empty($extensions)) {
  387.     // Munge the filename to protect against possible malicious extension hiding
  388.     // within an unknown file type (ie: filename.html.foo).
  389.     $file->filename = file_munge_filename($file->filename, $extensions);
  390.   }
  391.  
  392.   // Rename potentially executable files, to help prevent exploits (i.e. will
  393.   // rename filename.php.foo and filename.php to filename.php.foo.txt and
  394.   // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
  395.   // evaluates to TRUE.
  396.   if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|phar|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
  397.     $file->filemime = 'text/plain';
  398.     // The destination filename will also later be used to create the URI.
  399.     $file->filename .= '.txt';
  400.     // The .txt extension may not be in the allowed list of extensions. We have
  401.     // to add it here or else the file upload will fail.
  402.     if (!empty($extensions)) {
  403.       $validators['file_validate_extensions'][0] .= ' txt';
  404.       drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->filename]));
  405.     }
  406.   }
  407.  
  408.   // If the destination is not provided, use the temporary directory.
  409.   if (empty($destination)) {
  410.     $destination = 'temporary://';
  411.   }
  412.  
  413.   // Assert that the destination contains a valid stream.
  414.   $destination_scheme = file_uri_scheme($destination);
  415.   if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
  416.     drupal_set_message(t('The file could not be uploaded, because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
  417.     return FALSE;
  418.   }
  419.  
  420.   $file->source = $form_field_name;
  421.   // A URI may already have a trailing slash or look like "public://".
  422.   if (substr($destination, -1) != '/') {
  423.     $destination .= '/';
  424.   }
  425.   try {
  426.     $file->destination = file_destination($destination . $file->filename, $replace);
  427.   } catch (RuntimeException $e) {
  428.     drupal_set_message(t('The file %source could not be uploaded because the name is invalid.', ['%source' => $form_field_name]), 'error');
  429.     return FALSE;
  430.   }
  431.   // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  432.   // there's an existing file so we need to bail.
  433.   if ($file->destination === FALSE) {
  434.     drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', [
  435.       '%source' => $form_field_name,
  436.       '%directory' => $destination,
  437.     ]), 'error');
  438.     return FALSE;
  439.   }
  440.  
  441.   // Add in our check of the file name length.
  442.   $validators['file_validate_name_length'] = [];
  443.  
  444.   // Call the validation functions specified by this function's caller.
  445.   $errors = file_validate($file, $validators);
  446.  
  447.   // Check for errors.
  448.   if (!empty($errors)) {
  449.     $message = t('The specified file %name could not be uploaded.', ['%name' => $file->filename]);
  450.     if (count($errors) > 1) {
  451.       $message .= theme('item_list', ['items' => $errors]);
  452.     }
  453.     else {
  454.       $message .= ' ' . array_pop($errors);
  455.     }
  456.     form_set_error($form_field_name, $message);
  457.     return FALSE;
  458.   }
  459.  
  460.   // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
  461.   // directory. This overcomes open_basedir restrictions for future file
  462.   // operations.
  463.   $file->uri = $file->destination;
  464.   if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'], $file->uri)) {
  465.     form_set_error($form_field_name, t('File upload error. Could not move uploaded file.'));
  466.     watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', [
  467.       '%file' => $file->filename,
  468.       '%destination' => $file->uri,
  469.     ]);
  470.     return FALSE;
  471.   }
  472.  
  473.   // Set the permissions on the new file.
  474.   drupal_chmod($file->uri);
  475.  
  476.   // If we are replacing an existing file re-use its database record.
  477.   if ($replace == FILE_EXISTS_REPLACE) {
  478.     $existing_files = file_load_multiple([], ['uri' => $file->uri]);
  479.     if (count($existing_files)) {
  480.       $existing = reset($existing_files);
  481.       $file->fid = $existing->fid;
  482.     }
  483.   }
  484.  
  485.   // If we made it this far it's safe to record this file in the database.
  486.   if ($file = file_save($file)) {
  487.     // Track non-public files in the session if they were uploaded by an
  488.     // anonymous user. This allows modules such as the File module to only
  489.     // grant view access to the specific anonymous user who uploaded the file.
  490.     // See file_file_download().
  491.     // The 'file_public_schema' variable is used to allow other publicly
  492.     // accessible file schemes to be treated the same as the public:// scheme
  493.     // provided by Drupal core and to avoid adding unnecessary data to the
  494.     // session (and the resulting bypass of the page cache) in those cases. For
  495.     // security reasons, only schemes that are completely publicly accessible,
  496.     // with no download restrictions, should be added to this variable. See
  497.     // file_managed_file_value().
  498.     if (!$user->uid && !in_array($destination_scheme, variable_get('file_public_schema', ['public']))) {
  499.       $_SESSION['anonymous_allowed_file_ids'][$file->fid] = $file->fid;
  500.     }
  501.     // Add file to the cache.
  502.     $upload_cache[$form_field_name] = $file;
  503.     return $file;
  504.   }
  505.   return FALSE;
  506. }
  507.  
  508.  
  509. /**
  510.  * Create album
  511.  *
  512.  * @param $data
  513.  *
  514.  * @return DatabaseStatementInterface|int
  515.  * @throws Exception
  516.  */
  517. function dexp_photos_create_album($data) {
  518.  
  519.   $id = db_insert('dexp_album')
  520.     ->fields([
  521.       'title' => $data['title'],
  522.       'description' => !empty($data['description']) ? $data['description'] : "",
  523.       'uid' => $data['uid'],
  524.       'created' => !empty($data['created']) ? $data['created'] : REQUEST_TIME,
  525.     ])
  526.     ->execute();
  527.  
  528.   return $id;
  529.  
  530. }
  531.  
  532.  
  533. /**
  534.  * Load album by ID
  535.  *
  536.  * @param $id
  537.  *
  538.  * @return mixed
  539.  */
  540. function dexp_photos_load_album($id) {
  541.  
  542.   $result = db_select('dexp_album', 'a')
  543.     ->fields('a')
  544.     ->condition('id', $id)
  545.     ->execute()
  546.     ->fetchAssoc();
  547.  
  548.   return $result;
  549. }
  550.  
  551. /**
  552.  * Get albums
  553.  *
  554.  * @param $filter
  555.  *
  556.  * @return array
  557.  */
  558. function dexp_photos_get_albums($filter) {
  559.  
  560.   $skip = isset($filter->skip) ? $filter->skip : 0;
  561.   $limit = isset($filter->limit) ? $filter->limit : 100;
  562.   $order = isset($filter->order_by) ? $filter->order_by : [];
  563.   $where = isset($filter->where) ? $filter->where : [];
  564.  
  565.   $result = db_select('dexp_album', 'a')
  566.     ->fields('a');
  567.  
  568.   if (!empty($where)) {
  569.     foreach ($where as $w) {
  570.       $result = $result->condition($w->field, $w->value, isset($w->operator) ? $w->operator : '=');
  571.     }
  572.   }
  573.  
  574.  
  575.   if (!empty($order)) {
  576.     foreach ($order as $od) {
  577.       $result->orderBy($od->field, $od->value);
  578.     }
  579.   }
  580.   $result = $result->range($skip, $limit)
  581.     ->execute();
  582.  
  583.   $results = [];
  584.  
  585.  
  586.   while ($r = $result->fetchAssoc()) {
  587.     $item = $r;
  588.     $item['count'] = dexp_photos_count_photos($r['id']);
  589.     $item['photos'] = dexp_photos_load_album_photos($r['id'], 3, 0);
  590.  
  591.     $results[] = $item;
  592.   }
  593.  
  594.   return $results;
  595.  
  596. }
  597.  
  598. /**
  599.  * Update album
  600.  *
  601.  * @param $id
  602.  * @param $data
  603.  *
  604.  * @return DatabaseStatementInterface
  605.  */
  606. function dexp_photos_update_album($id, $data) {
  607.   return db_update('dexp_album')
  608.     ->fields([
  609.       'title' => $data['title'],
  610.       'description' => !empty($data['description']) ? $data['description'] : "",
  611.       'uid' => $data['uid'],
  612.     ])
  613.     ->condition('id', $id)
  614.     ->execute();
  615. }
  616.  
  617.  
  618. /**
  619.  * Delete files by Album ID
  620.  *
  621.  * @param $albumId
  622.  */
  623. function dexp_photos_delete_files($albumId) {
  624.   $results = db_select('dexp_photo', 'p')
  625.     ->fields('p', ['fid'])
  626.     ->condition('album_id', $albumId)
  627.     ->execute()
  628.     ->fetchCol();
  629.  
  630.   if (!empty($results)) {
  631.     foreach ($results as $fid) {
  632.  
  633.       $file = file_load($fid);
  634.       if ($file) {
  635.         file_delete($file);
  636.       }
  637.     }
  638.   }
  639.  
  640. }
  641.  
  642. /**
  643.  * Delete album by ID
  644.  *
  645.  * @param $id
  646.  *
  647.  * @return int
  648.  */
  649. function dexp_photos_delete_album($id) {
  650.  
  651.   $deleted = db_delete('dexp_album')
  652.     ->condition('id', $id)
  653.     ->execute();
  654.  
  655.   if ($deleted) {
  656.     dexp_photos_delete_files($id);
  657.     db_delete('dexp_photo')
  658.       ->condition('album_id', $id)
  659.       ->execute();
  660.   }
  661.  
  662.   return $deleted;
  663. }
  664.  
  665. /**
  666.  * Get photo counts
  667.  *
  668.  * @param $id
  669.  *
  670.  * @return mixed
  671.  */
  672.  
  673. function dexp_photos_count_photos($id) {
  674.  
  675.   $query = db_select('dexp_photo', 'p')
  676.     ->condition('album_id', $id);
  677.  
  678.   $num_rows = $query->countQuery()->execute()->fetchField();
  679.  
  680.  
  681.   return $num_rows;
  682. }
  683.  
  684. /**
  685.  * Get album photos
  686.  *
  687.  * @param $id
  688.  * @param $limit
  689.  * @param $skip
  690.  *
  691.  * @return array
  692.  */
  693. function dexp_photos_load_album_photos($id, $limit, $skip) {
  694.   $result = db_select('dexp_photo', 'p')
  695.     ->fields('p')
  696.     ->condition('album_id', $id);
  697.  
  698.   $result->leftJoin('file_managed', 'f', 'f.fid = p.fid');
  699.   $result->fields('f');
  700.  
  701.   $result = $result
  702.     ->orderBy('weight', 'ASC')
  703.     ->range($skip, $limit)
  704.     ->execute();
  705.  
  706.  
  707.   $items = [];
  708.  
  709.  
  710.   while ($r = $result->fetchAssoc()) {
  711.  
  712.     $item = [
  713.       'id' => $r['id'],
  714.       'fid' => $r['fid'],
  715.       'album_id' => $r['album_id'],
  716.       'weight' => $r['weight'],
  717.       'uid' => $r['uid'],
  718.       'title' => $r['title'],
  719.       'description' => $r['description'],
  720.       'created' => $r['created'],
  721.       'file' => [
  722.         'fid' => $r['fid'],
  723.         'filename' => $r['filename'],
  724.         'uri' => $r['uri'],
  725.         'thumbnail' => dexp_create_image_url($r['uri'], 'thumbnail'),
  726.         'preview' => dexp_create_image_url($r['uri']),
  727.         'filesize' => $r['filesize'],
  728.         'filemime' => $r['filemime'],
  729.       ],
  730.     ];
  731.  
  732.     $items[] = $item;
  733.   }
  734.  
  735.   return $items;
  736. }
  737.  
  738.  
  739. /**
  740.  * Create image url
  741.  *
  742.  * @param $uri
  743.  * @param null $style
  744.  *
  745.  * @return bool|string
  746.  */
  747. function dexp_create_image_url($uri, $style = NULL) {
  748.  
  749.   if (empty($style)) {
  750.     return file_create_url($uri);
  751.   }
  752.   $derivative_uri = image_style_path($style, $uri);
  753.   file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $uri, $derivative_uri);
  754.   $new_image_url = file_create_url($derivative_uri);
  755.  
  756.   return $new_image_url;
  757.  
  758. }
  759.  
  760. /**
  761.  * Update photo
  762.  *
  763.  * @param $id
  764.  * @param $data
  765.  *
  766.  * @return DatabaseStatementInterface
  767.  */
  768.  
  769. function dexp_photos_update_photo($id, $data) {
  770.  
  771.   return db_update('dexp_photo')
  772.     ->fields([
  773.       'title' => $data['title'],
  774.       'fid' => $data['fid'],
  775.       'description' => $data['description'],
  776.       'album_id' => $data['album_id'],
  777.       'weight' => $data['weight'],
  778.     ])
  779.     ->condition('id', $id)
  780.     ->execute();
  781. }
  782.  
  783.  
  784. function dexp_photo_get_max_photo_weight() {
  785.  
  786.   return db_query("SELECT MAX(weight) FROM {dexp_photo}")->fetchField();
  787. }
  788.  
  789. /**
  790.  * Create photo
  791.  *
  792.  * @param $data
  793.  *
  794.  * @return DatabaseStatementInterface|int
  795.  * @throws Exception
  796.  */
  797. function dexp_photos_create_photo($data) {
  798.  
  799.  
  800.   $id = db_insert('dexp_photo')
  801.     ->fields([
  802.       'title' => $data['title'],
  803.       'album_id' => $data['album_id'],
  804.       'description' => !empty($data['description']) ? $data['description'] : "",
  805.       'uid' => $data['uid'],
  806.       'fid' => $data['fid'],
  807.       'weight' => isset($data['weight']) ? $data['weight'] : dexp_photo_get_max_photo_weight() + 1,
  808.       'created' => !empty($data['created']) ? $data['created'] : REQUEST_TIME,
  809.     ])
  810.     ->execute();
  811.  
  812.   return $id;
  813. }
  814.  
  815.  
  816. /**
  817.  * Load photo
  818.  *
  819.  * @param $id
  820.  *
  821.  * @return mixed
  822.  */
  823. function dexp_photos_load_photo($id) {
  824.  
  825.   $result = db_select('dexp_photo', 'p')
  826.     ->fields('p')
  827.     ->condition('id', $id)
  828.     ->execute()
  829.     ->fetchAssoc();
  830.  
  831.   return $result;
  832. }
  833.  
  834.  
  835. /**
  836.  * Delete photo
  837.  *
  838.  * @param $id
  839.  *
  840.  * @return int
  841.  */
  842.  
  843. function dexp_photos_delete_photo($id) {
  844.  
  845.   return db_delete('dexp_photo')
  846.     ->condition('id', $id)
  847.     ->execute();
  848. }
  849.  
  850.  
  851. function dexp_photos_update_photos_weight($items) {
  852.  
  853.   $ids = [];
  854.  
  855.   foreach ($items as $item) {
  856.  
  857.     $id = db_update('dexp_photo')
  858.       ->fields([
  859.         'weight' => $item['weight'],
  860.       ])
  861.       ->condition('id', $item['id'])
  862.       ->execute();
  863.  
  864.     if ($id) {
  865.       $ids[] = $id;
  866.     }
  867.   }
  868.  
  869.   return $ids;
  870. }
  871.  
  872.  
  873. /**
  874.  * Migrate existing data from field images
  875.  * dexp_photos_migrate('field_homestead_photos', 'homestead', 'field_photos');
  876.  *
  877.  * @param string $fieldName
  878.  * @param string $bundle
  879.  * @param $newField
  880.  *
  881.  * @throws Exception
  882.  */
  883. function dexp_photos_migrate($fieldName = 'field_homestead_photos', $bundle = 'homestead', $newField = '') {
  884.  
  885.   $albums = NULL;
  886.   $map = NULL;
  887.   $fieldTable = 'field_data_' . $fieldName;
  888.   $query = db_query("SELECT * FROM {$fieldTable} as f INNER JOIN {node} AS n ON n.nid = f.entity_id WHERE f.entity_type = 'node' AND f.bundle = '$bundle'");
  889.  
  890.   $result = $query->fetchAll();
  891.  
  892.  
  893.   $weight = 0;
  894.  
  895.   foreach ($result as $item) {
  896.  
  897.     $nid = $item->nid;
  898.  
  899.     if (empty($albums[$nid])) {
  900.  
  901.       // create album
  902.       $albumId = dexp_photos_create_album([
  903.         'title' => t('Unsorted'),
  904.         'description' => '',
  905.         'uid' => $item->uid,
  906.       ]);
  907.  
  908.       $albums[$nid] = $albumId;
  909.  
  910.       $newFieldData = $newField . '_data';
  911.       $newFieldTable = 'field_data_' . $newField;
  912.       $insertData = [
  913.         'entity_type' => 'node',
  914.         'bundle' => $bundle,
  915.         'deleted' => 0,
  916.         'entity_id' => $nid,
  917.         'revision_id' => $nid,
  918.         'language' => 'und',
  919.         'delta' => 0,
  920.         $newFieldData => json_encode([$albumId]),
  921.       ];
  922.  
  923.       db_delete($newFieldTable)
  924.         ->condition('entity_type', 'node')
  925.         ->condition('entity_id', $nid)
  926.         ->condition('bundle', $bundle)->execute();
  927.  
  928.       db_insert($newFieldTable)
  929.         ->fields($insertData)->execute();
  930.  
  931.  
  932.     }
  933.     else {
  934.       $albumId = $albums[$nid];
  935.     }
  936.  
  937.  
  938.     $photoTitle = '';
  939.     $fieldAlt = $fieldName . "_alt";
  940.     $fieldTitle = $fieldName . "_title";
  941.     $fieldFid = $fieldName . "_fid";
  942.  
  943.     if (!empty($item->{$fieldAlt})) {
  944.       $photoTitle = $item->{$fieldAlt};
  945.     }
  946.     if (!empty($item->{$fieldTitle})) {
  947.       $photoTitle = $item->{$fieldTitle};
  948.     }
  949.  
  950.     dexp_photos_create_photo([
  951.       'album_id' => $albumId,
  952.       'uid' => $item->uid,
  953.       'title' => $photoTitle,
  954.       'fid' => $item->{$fieldFid},
  955.       'weight' => $weight,
  956.     ]);
  957.  
  958.     $weight++;
  959.  
  960.   }
  961.  
  962.   db_delete($fieldTable)->execute();
  963.  
  964. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement