Duffer Derek
<?php
namespace App\Repository\Copy;
use App\Repository\General\Async;
use App\Repository\General\Constants;
use App\Repository\General\DB;
use App\Repository\General\Log;
use App\Repository\Utils\CustomPodioAPI;
use App\Repository\Utils\PodioAuthRepo;
use Exception;
use PDO;
use Podio;
use PodioComment;
use PodioFile;
use PodioWidget;
/**
* Created by PhpStorm.
* User: jis
* Date: 29/3/17
* Time: 1:05 PM
*/
class WorkSpaceCopyRepo
{
private $customPodioAPI;
/**
* WorkSpaceRepo constructor.
*/
public function __construct()
{
$this->customPodioAPI = new CustomPodioAPI();
}
// copy-async/process-first-space?identifier=
public function processFirstSpace($identifier)
{
try {
Log::log("processFirstSpace $identifier started ", null, "info");
$sql = "select * from `work_spaces` where `copy_next_step` !='completed' and `identifier`=:identifier limit 1";
$STH = DB::prepare($sql);
$STH->execute(array(
'identifier' => $identifier,
));
$result = $STH->fetchAll(PDO::FETCH_ASSOC);
if (!$result || count($result) < 1) {
Log::log("all spaces are saved now, call for next step of the space $identifier ", null, "info");
print("DONEEEEEEEEEEEEE!!!!!!!!!!!!!!");
// print("http://podiomigration.bitkit.dk/copy-async/save-first-space-app-tasks?identifier=1");
// exit;
// Async::callAsync("copy-async/save-first-space-app-tasks?identifier=" . $identifier);
} else {
$space = $result[0];
$result = NULL;
$STH = NULL;
$repo = new PodioAuthRepo();
if ($repo->authenticate($identifier)) {
// if ($repo->authenticateSF($identifier)) {
Constants::setREFTYPE("workspace " . $identifier);
Constants::setREFID($space['src_space_id']);
$this->doNextStep($space);
} else {
Log::log("processFirstSpace authentication issue, identifier: " . $identifier, null, "warning");
}
}
} catch (\Exception $e) {
Log::logError($e . "", null, "processFirstSpace");
}
}
private function doNextStep($space)
{
try {
Log::log("WorkSpaceRepo doNextStep " . $space['copy_next_step'] . " " . $space['src_space_id'], $space);
if ($this->makeSureNextStepIsNotDoneBefore($space)) {
switch ($space['copy_next_step']) {
// run first 3 steps within the same process, after that start a new process
case "save_space":
$this->saveSpace($space);
break;
case "save_apps_in_space":
$this->saveAppsInSpace($space);
break;
case "save_members_in_space":
$this->saveMembersInSpace($space);
break;
case "process_first_app":
// start processing first app
// print("http://podiomigration.bitkit.dk/copy-async/process-first-app-in-the-space?identifier=1&space=" . $space['src_space_id']);
// exit;
// Async::callAsync("copy-async/process-first-app-in-the-space?identifier="
// . $space['identifier'] . "&space=" . $space['src_space_id']);
break;
case "save_workspace_streams":
break;
case "save_workspace_tasks":
break;
case "save_task_comments_files":
break;
}
}
// all steps completed
$this->markSpaceAsCompleted($space);
// call for next space
Async::callAsync("copy-async/process-first-space?identifier=" . $space['identifier']);
} catch (\Exception $e) {
Log::logError($e . "", $space, "doNextStep");
}
}
private function markSpaceAsCompleted($space)
{
// all steps in the space is completed - mark the space as completed
$sql = "UPDATE work_spaces SET copy_next_step=:copy_next_step WHERE id=:id";
$data = array("copy_next_step" => "completed", "id" => $space['id']);
$STH = DB::prepare($sql);
$STH->execute($data);
$STH = NULL;
}
private function makeSureNextStepIsNotDoneBefore(&$space)
{
$spaceSteps = array(
"save_space",
"save_apps_in_space",
"save_members_in_space",
"process_first_app",
"save_workspace_streams",
"save_workspace_tasks",
"save_task_comments_files"
);
if (in_array($space['copy_next_step'], $spaceSteps)) {
$pos = strpos($space['copy_completed_steps'], $space['copy_next_step']);
if ($pos === false) {
return true;
}
// already completed 'copy_next_step'
// find the first not completed step
foreach ($spaceSteps as $step) {
$pos = strpos($space['copy_completed_steps'], $step);
if ($pos === false) {
$space['copy_next_step'] = $step; // make this step as 'copy_next_step'
return true;
}
}
// mark space as completed
$space['copy_next_step'] = "completed";
$this->markSpaceAsCompleted($space);
}
return false;
}
private function saveSpace($space)
{
try {
$workSpace = $this->customPodioAPI->podioGet("/space/" . $space['src_space_id']);
if ($workSpace) {
$sql = "UPDATE work_spaces SET src_org_id =:src_org_id,src_name=:src_name,
`src_space_url`=:src_space_url,`type`=:type,`role`=:role,
copy_next_step=:copy_next_step,copy_completed_steps=:copy_completed_steps,
src_org_url_label=:src_org_url_label,src_space_url_label=:src_space_url_label,widgets=:widgets WHERE id=:id";
$widgets = $this->getWidget($space);
$data = array(
"copy_next_step" => "save_apps_in_space",
"id" => $space['id'],
"src_org_id" => $workSpace['org_id'],
"src_name" => $workSpace['name'],
"type" => $workSpace['type'],
"role" => $workSpace['role'],
"copy_completed_steps" => "save_space",
'src_space_url' => $workSpace['url'],
'src_org_url_label' => $workSpace['org']['url_label'],
'src_space_url_label' => $workSpace['url_label'],
'widgets' => $widgets
);
$STH = DB::prepare($sql);
$STH->execute($data);
$space['copy_next_step'] = "save_apps_in_space";
// exit;
$this->doNextStep($space);
}
} catch (\Exception $e) {
Log::logError($e . "", $space, "saveSpace");
}
}
private function getWidget($space)
{
try {
$widgets = $this->customPodioAPI->podioGet("/widget/space/" . $space['src_space_id']);
return json_encode($widgets);
} catch (\Exception $e) {
Log::logError($e . "", $space, "saveWidget");
}
return NULL;
}
private function saveAppsInSpace($space)
{
try {
$workSpaceApps = $this->customPodioAPI->podioGet("/app/space/" . $space['src_space_id'] . "/");
if ($workSpaceApps && is_array($workSpaceApps)) {
//list the app_ids to be copied
// $allowedApps = [15476991];
$sql = "INSERT IGNORE INTO apps (identifier,src_space_id,src_app_id,src_name,src_config,
copy_next_step,create_next_step) VALUES
(:identifier,:src_space_id,:src_app_id,:src_name,:src_config,:copy_next_step,:create_next_step)";
$STH = DB::prepare($sql);
$data = array(
"identifier" => $space['identifier'],
"src_space_id" => $space['src_space_id'],
"copy_next_step" => "save_app",
"create_next_step" => "clone_or_create_app"
);
foreach ($workSpaceApps as $app) {
// Skip apps not in allow-list
// if (!in_array($app['app_id'], $allowedApps)) {
// continue;
// }
$data["src_app_id"] = $app['app_id'];
$data["src_name"] = $app['config']['name'];
$appData = $this->customPodioAPI->podioGet("/app/" . $app['app_id'] . "/");
$data["src_config"] = json_encode($appData['config']);
$STH->execute($data);
}
}
$this->updateNextStep($space, "save_members_in_space", ", save_apps_in_space");
} catch (\Exception $e) {
Log::logError($e . "", $space, "saveAppsInSpace");
}
}
public function saveContactApp($identifier)
{
try {
$repo = new PodioAuthRepo();
if ($repo->authenticate($identifier)) {
$spaceContactAppId = 18365579;
$podioApp = $this->customPodioAPI->podioGet("/app/" . $spaceContactAppId);
if ($podioApp) {
$srcFields = $podioApp['fields'];
$srcFields = json_encode($srcFields);
$sql = "INSERT IGNORE INTO contact_app SET identifier=:identifier,src_config=:src_config,src_fields =:src_fields";
$data = array("identifier" => $identifier, "src_fields" => $srcFields, 'src_config' => json_encode($podioApp['config']));
$STH = DB::prepare($sql);
$STH->execute($data);
$STH = NULL;
} else {
Log::log("saveApp Contact App is Null", $spaceContactAppId, "warning");
}
}
} catch (\Exception $e) {
Log::logError($e . "", $spaceContactAppId, "saveApp");
}
}
public function saveArchivedApps($identifier)
{
$repo = new PodioAuthRepo();
if ($repo->authenticate($identifier)) {
$sql = "select * from `work_spaces` where `identifier`=:identifier";
$STH = DB::prepare($sql);
$STH->execute(array(
'identifier' => $identifier,
));
$result = $STH->fetchAll(PDO::FETCH_ASSOC);
if ($result && count($result) > 0) {
foreach ($result as $space) {
$this->saveArchivedAppsInSpace($space);
}
}
}
}
private function saveArchivedAppsInSpace($space)
{
try {
$attributes = array(
'include_inactive' => true
);
$workSpaceApps = $this->customPodioAPI->podioGet("/app/space/" . $space['src_space_id'] . "/", $attributes);
if ($workSpaceApps && is_array($workSpaceApps)) {
$sql = "INSERT IGNORE INTO apps (identifier,src_space_id,src_app_id,src_name,src_config,
copy_next_step,create_next_step,src_app_status) VALUES
(:identifier,:src_space_id,:src_app_id,:src_name,:src_config,:copy_next_step,:create_next_step,:src_app_status)";
$STH = DB::prepare($sql);
$data = array(
"identifier" => $space['identifier'],
"src_space_id" => $space['src_space_id'],
"copy_next_step" => "save_app",
"create_next_step" => "clone_or_create_app",
'src_app_status' => 'inactive'
);
foreach ($workSpaceApps as $app) {
if ($app['status'] == 'inactive') {
$data["src_app_id"] = $app['app_id'];
$data["src_name"] = $app['config']['name'];
$data["src_config"] = json_encode($app['config']);
$STH->execute($data);
}
}
}
$this->updateNextStep($space, "save_members_in_space", ", save_apps_in_space");
} catch (\Exception $e) {
Log::logError($e . "", $space, "saveAppsInSpace");
}
}
/**
* @param $space
*/
private function saveMembersInSpace($space)
{
try {
$limit = 100;
$offset = 0;
$attributes = array("limit" => $limit);
$sql = "INSERT IGNORE INTO workspace_members ( `identifier`, `src_space_id`, `name`, `profile_id`, `user_id`, `email`, `role`) VALUES
( :identifier, :src_space_id, :name, :profile_id, :user_id, :email, :role)";
$STH = DB::prepare($sql);
$data = array("identifier" => $space['identifier'], "src_space_id" => $space['src_space_id']);
do {
$attributes['offset'] = $offset;
$count = 0;
$workSpaceMembers = $this->customPodioAPI->podioGet("/space/" . $space['src_space_id'] . "/member/", $attributes);
if ($workSpaceMembers && is_array($workSpaceMembers) && count($workSpaceMembers) > 0) {
$count = count($workSpaceMembers);
foreach ($workSpaceMembers as $contact) {
$data['role'] = $contact['role'];
$data['user_id'] = $contact['profile']['user_id'];
$data['profile_id'] = $contact['profile']['profile_id'];
$data['name'] = $contact['profile']['name'];
$data['email'] = $contact['user']['mail'];
$STH->execute($data);
}
Log::log("saveMembersInSpace " . $space['copy_next_step'], $workSpaceMembers);
$offset += $limit;
}
} while ($count > 0);
// $this->saveSpaceContacts($space['src_space_id']);
$this->updateNextStep($space, "process_first_app", ", save_members_in_space");
} catch (\Exception $e) {
Log::logError($e . "", $space, "saveMembersInSpace");
}
}
public function saveSpaceContacts($spaceId)
{
try {
$sql = "INSERT INTO `workspace_contacts` (`src_space_id`,`profile_id`,`fields`) VALUES (:src_space_id, :profile_id,
:fields)";
$STH = DB::prepare($sql);
$limit = 100;
$offset = 0;
$attributes = array("limit" => $limit);
do {
$attributes['offset'] = $offset;
$count = 0;
$contacts = $this->customPodioAPI->podioGet("/contact/space/$spaceId/?contact_type=space&exclude_self=true&order=name", $attributes);
if ($contacts && is_array($contacts) && count($contacts) > 0) {
$count = count($contacts);
$offset += $limit;
foreach ($contacts as $contact) {
$profile_id = NULL;
$src_space_id = NULL;
foreach ($contact as $type => $values) {
switch ($type) {
case "profile_id":
$profile_id = $values;
break;
case "space_id":
$src_space_id = (int)$values;
break;
}
}
$data = array("src_space_id" => $src_space_id, "profile_id" => $profile_id, "fields" => json_encode($contact));
$STH->execute($data);
}
}
} while ($count > 0);
$STH = NULL;
} catch (\Exception $e) {
Log::logError($e . "", array($spaceId), "saveSpaceContacts");
}
}
private function updateNextStep($space, $nextStep, $currentStep)
{
$sql = "UPDATE work_spaces SET copy_next_step=:copy_next_step,copy_completed_steps=CONCAT(COALESCE(copy_completed_steps,''),:copy_completed_steps) WHERE id=:id";
$data = array("copy_next_step" => $nextStep, "id" => $space['id'], "copy_completed_steps" => $currentStep);
$STH = DB::prepare($sql);
$STH->execute($data);
$space['copy_next_step'] = $nextStep;
// exit;
$this->doNextStep($space);
}
/**+
* Save all workspaces to DB
* @param $spaces
* @param $identifier
*/
public function saveAllSpaces($spaces, $identifier)
{
$sql = "INSERT INTO work_spaces (identifier,src_space_id,copy_next_step,create_next_step)
VALUES(:identifier,:src_space_id,:copy_next_step,:create_next_step)";
$data = array("copy_next_step" => "save_space", "create_next_step" => "create_space_and_clone_all_apps", "identifier" => $identifier);
$STH = DB::prepare($sql);
foreach ($spaces as $space) {
$data['src_space_id'] = $space;
$STH->execute($data);
}
}
public function copySpaceFiles($identifier)
{
try {
$repo = new PodioAuthRepo();
// if ($repo->authenticateSF($identifier)) {
if ($repo->authenticate($identifier)) {
Log::log("copySpaceFiles-$identifier started ", null, "info");
$sql = "select src_space_id from `work_spaces` where identifier=:identifier ";
$STH = DB::prepare($sql);
$STH->execute(array(
'identifier' => $identifier,
));
$result = $STH->fetchAll(PDO::FETCH_ASSOC);
if ($result && count($result) > 0) {
foreach ($result as $space) {
$offset = 0;
$limit = 20;
$fileRepo = new FileCopyRepo();
do {
$count = 0;
$attributes = array(
'attached_to' => "space",
'sort_by' => 'created_on',
'sort_desc' => 'false',
'limit' => $limit,
'offset' => $offset
);
$spaceFiles = $this->customPodioAPI->podioGet("/file/space/" . $space['src_space_id'] . "/", $attributes);
if ($spaceFiles && is_array($spaceFiles) && count($spaceFiles) > 0) {
$count = count($spaceFiles);
$fileRepo->saveFilesToDB(array(
"identifier" => $identifier,
'src_ref_type' => "space",
'src_ref_id' => $space['src_space_id']
), $spaceFiles);
}
$offset += $limit;
// $options = array('silent' => true, 'hook' => false);
// $count = count($spaceFiles);
// $offset += $limit;
// foreach ($spaceFiles as $file) {
// $attr = array(
// 'value' => $this->streamFilesUploadedByComment($file),
// );
// $fileCopy = PodioFile::copy($file->file_id);
// $attachToItem = PodioFile::attach($fileCopy->file_id, $attributes = array('ref_type' => 'space',
// 'ref_id' => intval($space['target_space_id'])));
// PodioComment::create('file', $fileCopy->file_id, $attr, $options);
// }
} while ($count >= $limit);
Log::log("copySpaceFiles- finished " . $space['src_space_id'], null, "info");
}
}
Log::log("copySpaceFiles-$identifier finished ", null, "info");
}
} catch (Exception $e) {
}
}
}
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists