<?php
/*
Plugin Name: Save And Copy
Description: Add "Save & Copy" button to edit pages that copies record and uploads.
Version: 1.07
CMS Version Required: 3.00
*/


// DON'T UPDATE ANYTHING BELOW THIS LINE
require_once "saveAndCopy.js.php";



addAction('admin_head',   'saveAsCopy_addJavascript',    null, 0);
addAction('section_init', 'saveAsCopy_copyUploads_ajax', null, 0);
addFilter('adminUI_args', 'saveAsCopy_addButton');

// show "Save & Copy" button
function saveAsCopy_addButton($adminUI_args, $tableName, $action) {

  // Insert button after [Save] like this "[Save] [Save & Copy] [Cancel]" to match button order in: Admin > Section Editors > Field Editor
  $menuType  = @$GLOBALS['schema']['menuType'];
  $addButton = isset($menuType) && ($menuType == 'multi' || $menuType == 'category') && ($action == 'add' || $action == 'edit');
  if ($addButton) {
    array_splice($adminUI_args['BUTTONS'], 1, 0, [[
      'label'   => t('Save & Copy'),
      'name'    => '_action=save',
      'type'    => 'button',
      'onclick' => 'window.SAVE_AS_COPY_CLICKED=true; $(\'form\')[0].onsubmit(); $(\'form\').submit();',
    ]]);
  }

  //
  return $adminUI_args;
}

//
function saveAsCopy_copyUploads_ajax() {

  // only run when requested by ajax
  // eg: _plugin=saveAsCopy&_pluginAction=copy&tableName=...&recordNum=...&preSaveTempId=...
  if (@$_REQUEST['_plugin']       != 'saveAsCopy') { return; }
  if (@$_REQUEST['_pluginAction'] != 'copy')       { return; }

  //
  $tableName           = @$_REQUEST['menu'];
  $sourceRecordNum     = @$_REQUEST['recordNum'];
  $targetPreSaveTempId = @$_REQUEST['preSaveTempId'];

  // check if user has access to source record
  displaySectionAccessErrors('');

  // remove expired uploads
  removeExpiredUploads();

  // load list of non-thumb uploads from source record
  $where   = mysql_escapef("tableName = ? AND recordNum = ? ORDER BY `order`", $tableName, $sourceRecordNum);
  $uploads = mysql_select("uploads", $where);

  // re-upload each file for targetPreSaveTempId
  $errors = '';
  foreach ($uploads as $upload) {

    // get source path - fixed bug where files wouldn't copy after upload paths were switched to relative in CMS 2.09
    $fieldSchema = $GLOBALS['schema'][ $upload['fieldName'] ];
    list($uploadDir, $uploadUrl) = getUploadDirAndUrl($fieldSchema);
    $sourcePath  = $uploadDir .'/'. $upload['filePath'];

    //
    $errors    .= saveUploadFromFilepath($upload['tableName'], $upload['fieldName'], null, $targetPreSaveTempId, $sourcePath );

    if (!$errors) {
      // Copying Info Data - UCS-750794
      // Add info items
      // Get last inserted id for table num column (mysql_insert_id) and update record
      $uploadNum    = mysql_insert_id();
      $where        = mysql_escapef("num = ? AND tableName = ? AND fieldName = ?", $uploadNum, @$upload['tableName'], @$upload['fieldName']);
      $colsToValues = array(
        'info1' => @$upload['info1'],
        'info2' => @$upload['info2'],
        'info3' => @$upload['info3'],
        'info4' => @$upload['info4'],
        'info5' => @$upload['info5'],
      );
      mysql_update("uploads", null, $where, $colsToValues);
    }
  }

  if ($errors) { die($errors) ; }
  exit;
}

?>
