Example #1
0
 public function createProject()
 {
     // project name sanitize
     $oldName = $this->projectStructure['project_name'];
     $this->projectStructure['project_name'] = $this->_sanitizeName($this->projectStructure['project_name']);
     if ($this->projectStructure['project_name'] == false) {
         $this->projectStructure['result']['errors'][] = array("code" => -5, "message" => "Invalid Project Name " . $oldName . ": it should only contain numbers and letters!");
         return false;
     }
     // create project?
     $this->projectStructure['ppassword'] = $this->_generatePassword();
     $this->projectStructure['user_ip'] = Utils::getRealIpAddr();
     $this->projectStructure['id_project'] = insertProject($this->projectStructure);
     //create user (Massidda 2013-01-24)
     //check if all the keys are valid MyMemory keys
     if (!empty($this->projectStructure['private_tm_key'])) {
         foreach ($this->projectStructure['private_tm_key'] as $i => $_tmKey) {
             $this->tmxServiceWrapper->setTmKey($_tmKey['key']);
             try {
                 $keyExists = $this->tmxServiceWrapper->checkCorrectKey();
                 if (!isset($keyExists) || $keyExists === false) {
                     Log::doLog(__METHOD__ . " -> TM key is not valid.");
                     throw new Exception("TM key is not valid: " . $_tmKey['key'], -4);
                 }
             } catch (Exception $e) {
                 $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                 return false;
             }
             //set the first key as primary
             $this->tmxServiceWrapper->setTmKey($this->projectStructure['private_tm_key'][0]['key']);
         }
         //check if the MyMemory keys provided by the user are already associated to him.
         if ($this->projectStructure['userIsLogged']) {
             $mkDao = new TmKeyManagement_MemoryKeyDao($this->dbHandler);
             $searchMemoryKey = new TmKeyManagement_MemoryKeyStruct();
             $searchMemoryKey->uid = $this->projectStructure['uid'];
             $userMemoryKeys = $mkDao->read($searchMemoryKey);
             $userTmKeys = array();
             $memoryKeysToBeInserted = array();
             //extract user tm keys
             foreach ($userMemoryKeys as $_memoKey) {
                 /**
                  * @var $_memoKey TmKeyManagement_MemoryKeyStruct
                  */
                 $userTmKeys[] = $_memoKey->tm_key->key;
             }
             foreach ($this->projectStructure['private_tm_key'] as $_tmKey) {
                 if (!in_array($_tmKey['key'], $userTmKeys)) {
                     $newMemoryKey = new TmKeyManagement_MemoryKeyStruct();
                     $newTmKey = new TmKeyManagement_TmKeyStruct();
                     $newTmKey->key = $_tmKey['key'];
                     $newTmKey->tm = true;
                     $newTmKey->glos = true;
                     //TODO: take this from input
                     $newTmKey->name = $_tmKey['name'];
                     $newMemoryKey->tm_key = $newTmKey;
                     $newMemoryKey->uid = $this->projectStructure['uid'];
                     $memoryKeysToBeInserted[] = $newMemoryKey;
                 } else {
                     Log::doLog('skip insertion');
                 }
             }
             try {
                 $mkDao->createList($memoryKeysToBeInserted);
             } catch (Exception $e) {
                 Log::doLog($e->getMessage());
                 # Here we handle the error, displaying HTML, logging, ...
                 $output = "<pre>\n";
                 $output .= $e->getMessage() . "\n\t";
                 $output .= "</pre>";
                 Utils::sendErrMailReport($output);
             }
         }
         //the base case is when the user clicks on "generate private TM" button:
         //a (user, pass, key) tuple is generated and can be inserted
         //if it comes with it's own key without querying the creation API, create a (key,key,key) user
         if (empty($this->projectStructure['private_tm_user'])) {
             $this->projectStructure['private_tm_user'] = $this->projectStructure['private_tm_key'][0]['key'];
             $this->projectStructure['private_tm_pass'] = $this->projectStructure['private_tm_key'][0]['key'];
         }
         insertTranslator($this->projectStructure);
     }
     //sort files in order to process TMX first
     $sortedFiles = array();
     foreach ($this->projectStructure['array_files'] as $fileName) {
         //check for glossary files and tmx and put them in front of the list
         $infoFile = DetectProprietaryXliff::getInfo($fileName);
         if (DetectProprietaryXliff::getMemoryFileType()) {
             //found TMX, enable language checking routines
             if (DetectProprietaryXliff::isTMXFile()) {
                 $this->checkTMX = 1;
             }
             //not used at moment but needed if we want to do a poll for status
             if (DetectProprietaryXliff::isGlossaryFile()) {
                 $this->checkGlossary = 1;
             }
             //prepend in front of the list
             array_unshift($sortedFiles, $fileName);
         } else {
             //append at the end of the list
             array_push($sortedFiles, $fileName);
         }
     }
     $this->projectStructure['array_files'] = $sortedFiles;
     unset($sortedFiles);
     $uploadDir = $this->uploadDir = INIT::$UPLOAD_REPOSITORY . DIRECTORY_SEPARATOR . $this->projectStructure['uploadToken'];
     //we are going to access the storage, get model object to manipulate it
     $this->fileStorage = new FilesStorage();
     $linkFiles = $this->fileStorage->getHashesFromDir($this->uploadDir);
     /*
         loop through all input files to
         1) upload TMX and Glossaries
     */
     try {
         $this->_pushTMXToMyMemory();
     } catch (Exception $e) {
         //exit project creation
         return false;
     }
     //TMX Management
     /*
        loop through all input files to
        2)convert, in case, non standard XLIFF files to a format that Matecat understands
     
        Note that XLIFF that don't need conversion are moved anyway as they are to cache in order not to alter the workflow
     */
     foreach ($this->projectStructure['array_files'] as $fileName) {
         /*
           Conversion Enforce
           Checking Extension is no more sufficient, we want check content
           $enforcedConversion = true; //( if conversion is enabled )
         */
         $isAFileToConvert = $this->isConversionToEnforce($fileName);
         //if it's one of the listed formats or conversion is not enabled in first place
         if (!$isAFileToConvert) {
             /*
               filename is already an xliff and it's in upload directory
               we have to make a cache package from it to avoid altering the original path
             */
             //get file
             $filePathName = "{$this->uploadDir}/{$fileName}";
             //calculate hash + add the fileName, if i load 3 equal files with the same content
             // they will be squashed to the last one
             $sha1 = sha1_file($filePathName);
             //make a cache package (with work/ only, emtpy orig/)
             $this->fileStorage->makeCachePackage($sha1, $this->projectStructure['source_language'], false, $filePathName);
             //put reference to cache in upload dir to link cache to session
             $this->fileStorage->linkSessionToCache($sha1, $this->projectStructure['source_language'], $this->projectStructure['uploadToken'], $fileName);
             //add newly created link to list
             $linkFiles['conversionHashes']['sha'][] = $sha1 . "|" . $this->projectStructure['source_language'];
             $linkFiles['conversionHashes']['fileName'][$sha1 . "|" . $this->projectStructure['source_language']][] = $fileName;
             //when the same sdlxliff is uploaded more than once with different names
             $linkFiles['conversionHashes']['sha'] = array_unique($linkFiles['conversionHashes']['sha']);
             unset($sha1);
         }
     }
     //now, upload dir contains only hash-links
     //we start copying files to "file" dir, inserting metadata in db and extracting segments
     foreach ($linkFiles['conversionHashes']['sha'] as $linkFile) {
         //converted file is inside cache directory
         //get hash from file name inside UUID dir
         $hashFile = FilesStorage::basename_fix($linkFile);
         $hashFile = explode('|', $hashFile);
         //use hash and lang to fetch file from package
         $cachedXliffFilePathName = $this->fileStorage->getXliffFromCache($hashFile[0], $hashFile[1]);
         //get sha
         $sha1_original = $hashFile[0];
         //associate the hash to the right file in upload directory
         //get original file name, to insert into DB and cp in storage
         //PLEASE NOTE, this can be an array when the same file added more
         // than once and with different names
         $_originalFileName = $linkFiles['conversionHashes']['fileName'][$linkFile];
         unset($hashFile);
         if (!file_exists($cachedXliffFilePathName)) {
             $this->projectStructure['result']['errors'][] = array("code" => -6, "message" => "File not found on server after upload.");
         }
         try {
             $info = FilesStorage::pathinfo_fix($cachedXliffFilePathName);
             if (!in_array($info['extension'], array('xliff', 'sdlxliff', 'xlf'))) {
                 throw new Exception("Failed to find Xliff - no segments found", -3);
             }
             $yearMonthPath = date_create($this->projectStructure['create_date'])->format('Ymd');
             $fileDateSha1Path = $yearMonthPath . DIRECTORY_SEPARATOR . $sha1_original;
             //PLEASE NOTE, this can be an array when the same file added more
             // than once and with different names
             foreach ($_originalFileName as $originalFileName) {
                 $mimeType = FilesStorage::pathinfo_fix($originalFileName, PATHINFO_EXTENSION);
                 $fid = insertFile($this->projectStructure, $originalFileName, $mimeType, $fileDateSha1Path);
                 //move the file in the right directory from the packages to the file dir
                 $this->fileStorage->moveFromCacheToFileDir($fileDateSha1Path, $this->projectStructure['source_language'], $fid, $originalFileName);
                 $this->projectStructure['file_id_list']->append($fid);
                 $this->_extractSegments(file_get_contents($cachedXliffFilePathName), $fid);
             }
         } catch (Exception $e) {
             if ($e->getCode() == -1) {
                 $this->projectStructure['result']['errors'][] = array("code" => -1, "message" => "No text to translate in the file {$originalFileName}.");
                 $this->fileStorage->deleteHashFromUploadDir($this->uploadDir, $linkFile);
             } elseif ($e->getCode() == -2) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store segments in database for {$originalFileName}");
             } elseif ($e->getCode() == -3) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "File {$originalFileName} not found. Failed to save XLIFF conversion on disk");
             } elseif ($e->getCode() == -4) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Internal Error. Xliff Import: Error parsing. ( {$originalFileName} )");
             } elseif ($e->getCode() == -11) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files on disk. Permission denied");
             } elseif ($e->getCode() == -12) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files in database");
             } elseif ($e->getCode() == -13) {
                 $this->projectStructure['result']['errors'][] = array("code" => -13, "message" => $e->getMessage());
                 Log::doLog($e->getMessage());
                 return null;
                 // SEVERE EXCEPTION we can not write to disk!! Break project creation
             } else {
                 //mysql insert Blob Error
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to create project. Database Error on {$originalFileName}. Please try again.");
             }
             Log::doLog($e->getMessage());
             Log::doLog($e->getTraceAsString());
         }
     }
     //end of conversion hash-link loop
     try {
         $this->_zipFileHandling($linkFiles);
     } catch (Exception $e) {
         //exit project creation
         return false;
     }
     //check if the files language equals the source language. If not, set an error message.
     if (!$this->projectStructure['skip_lang_validation']) {
         $this->validateFilesLanguages();
     }
     if (!$this->_doCheckForErrors()) {
         //exit project creation
         return false;
     }
     //Log::doLog( array_pop( array_chunk( $SegmentTranslations[$fid], 25, true ) ) );
     //create job
     if (isset($_SESSION['cid']) and !empty($_SESSION['cid'])) {
         $owner = $_SESSION['cid'];
     } else {
         $_SESSION['_anonym_pid'] = $this->projectStructure['id_project'];
         //default user
         $owner = '';
     }
     $isEmptyProject = false;
     //Throws exception
     try {
         $this->_createJobs($this->projectStructure, $owner);
         //FIXME for project with pre translation this query is not enough,
         //we need compare the number of segments with translations, but take an eye to the opensource
         $query_visible_segments = "SELECT count(*) as cattool_segments\n\t\t\t\tFROM segments WHERE id_file IN ( %s ) and show_in_cattool = 1";
         $string_file_list = implode(",", $this->projectStructure['file_id_list']->getArrayCopy());
         $query_visible_segments = sprintf($query_visible_segments, $string_file_list);
         try {
             $rows = $this->dbHandler->fetch_array($query_visible_segments);
         } catch (PDOException $e) {
             Log::doLog("Segment Search: Failed Retrieve min_segment/max_segment for files ( {$string_file_list} ) - DB Error: {$e->getMessage()} - \n");
             throw new Exception("Segment Search: Failed Retrieve min_segment/max_segment for job", -5);
         }
         if ($rows[0]['cattool_segments'] == 0) {
             Log::doLog("Segment Search: No segments in this project - \n");
             $isEmptyProject = true;
         }
     } catch (Exception $ex) {
         $this->projectStructure['result']['errors'][] = array("code" => -9, "message" => "Fail to create Job. ( {$ex->getMessage()} )");
         return false;
     }
     try {
         Utils::deleteDir($this->uploadDir);
         if (is_dir($this->uploadDir . '_converted')) {
             Utils::deleteDir($this->uploadDir . '_converted');
         }
     } catch (Exception $e) {
         $output = "<pre>\n";
         $output .= " - Exception: " . print_r($e->getMessage(), true) . "\n";
         $output .= " - REQUEST URI: " . print_r(@$_SERVER['REQUEST_URI'], true) . "\n";
         $output .= " - REQUEST Message: " . print_r($_REQUEST, true) . "\n";
         $output .= " - Trace: \n" . print_r($e->getTraceAsString(), true) . "\n";
         $output .= "\n\t";
         $output .= "Aborting...\n";
         $output .= "</pre>";
         Log::doLog($output);
         Utils::sendErrMailReport($output, $e->getMessage());
     }
     $this->projectStructure['status'] = INIT::$VOLUME_ANALYSIS_ENABLED ? Constants_ProjectStatus::STATUS_NEW : Constants_ProjectStatus::STATUS_NOT_TO_ANALYZE;
     if ($isEmptyProject) {
         $this->projectStructure['status'] = Constants_ProjectStatus::STATUS_EMPTY;
     }
     $this->projectStructure['result']['code'] = 1;
     $this->projectStructure['result']['data'] = "OK";
     $this->projectStructure['result']['ppassword'] = $this->projectStructure['ppassword'];
     $this->projectStructure['result']['password'] = $this->projectStructure['array_jobs']['job_pass'];
     $this->projectStructure['result']['id_job'] = $this->projectStructure['array_jobs']['job_list'];
     $this->projectStructure['result']['job_segments'] = $this->projectStructure['array_jobs']['job_segments'];
     $this->projectStructure['result']['id_project'] = $this->projectStructure['id_project'];
     $this->projectStructure['result']['project_name'] = $this->projectStructure['project_name'];
     $this->projectStructure['result']['source_language'] = $this->projectStructure['source_language'];
     $this->projectStructure['result']['target_language'] = $this->projectStructure['target_language'];
     $this->projectStructure['result']['status'] = $this->projectStructure['status'];
     $this->projectStructure['result']['lang_detect'] = $this->projectStructure['lang_detect_files'];
     $query_project_summary = "\n            SELECT\n                 COUNT( s.id ) AS project_segments,\n                 SUM( IF( IFNULL( st.eq_word_count, -1 ) = -1, s.raw_word_count, st.eq_word_count ) ) AS project_raw_wordcount\n            FROM segments s\n            INNER JOIN files_job fj ON fj.id_file = s.id_file\n            INNER JOIN jobs j ON j.id= fj.id_job\n            LEFT JOIN segment_translations st ON s.id = st.id_segment\n            WHERE j.id_project = %u\n        ";
     $query_project_summary = sprintf($query_project_summary, $this->projectStructure['id_project']);
     $project_summary = $this->dbHandler->fetch_array($query_project_summary);
     $update_project_count = "\n            UPDATE projects\n              SET\n                standard_analysis_wc = %.2F,\n                status_analysis = '%s'\n            WHERE id = %u\n        ";
     $update_project_count = sprintf($update_project_count, $project_summary[0]['project_raw_wordcount'], $this->projectStructure['status'], $this->projectStructure['id_project']);
     $this->dbHandler->query($update_project_count);
     //        Log::doLog( $this->projectStructure );
     //create Project into DQF queue
     if (INIT::$DQF_ENABLED && !empty($this->projectStructure['dqf_key'])) {
         $dqfProjectStruct = DQF_DqfProjectStruct::getStruct();
         $dqfProjectStruct->api_key = $this->projectStructure['dqf_key'];
         $dqfProjectStruct->project_id = $this->projectStructure['id_project'];
         $dqfProjectStruct->name = $this->projectStructure['project_name'];
         $dqfProjectStruct->source_language = $this->projectStructure['source_language'];
         $dqfQueue = new Analysis_DqfQueueHandler();
         try {
             $projectManagerInfo = $dqfQueue->checkProjectManagerKey($this->projectStructure['dqf_key']);
             $dqfQueue->createProject($dqfProjectStruct);
             //for each job, push a task into AMQ's DQF queue
             foreach ($this->projectStructure['array_jobs']['job_list'] as $i => $jobID) {
                 /**
                  * @var $dqfTaskStruct DQF_DqfTaskStruct
                  */
                 $dqfTaskStruct = DQF_DqfTaskStruct::getStruct();
                 $dqfTaskStruct->api_key = $this->projectStructure['dqf_key'];
                 $dqfTaskStruct->project_id = $this->projectStructure['id_project'];
                 $dqfTaskStruct->task_id = $jobID;
                 $dqfTaskStruct->target_language = $this->projectStructure['target_language'][$i];
                 $dqfTaskStruct->file_name = uniqid('', true) . $this->projectStructure['project_name'];
                 $dqfQueue->createTask($dqfTaskStruct);
             }
         } catch (Exception $exn) {
             $output = __METHOD__ . " (code " . $exn->getCode() . " ) - " . $exn->getMessage();
             Log::doLog($output);
             Utils::sendErrMailReport($output, $exn->getMessage());
         }
     }
 }
                        $saveDir = insertFolder($service, $reportFolderName, $gProjectDir->getId());
                    }
                    $properties = [
                        [
                            'key' => 'isAsanaGDocReport',
                            'value' => 'true',
                            'visibility' => 'PUBLIC',

                        ],
                        [
                            'key' => 'asanaClientName',
                            'value' => $clientName,
                            'visibility' => 'PUBLIC',
                        ]
                    ];
                    removeFileIfExists($service, $fileReportName, $saveDir->getId());
                    logMessage("Sending file '" . $fileReportName . "' to google drive");
                    $insertedFile = insertFile($service, $fileReportName, '', $saveDir->getId(), GDOC_SHEET_MIME,
                        $fileReport, $properties);
//                        insertPermission($service, $insertedFile->getId() , $user->emailAddress, 'user', 'owner'  );
                    reportMessage("<a href='https://docs.google.com/spreadsheets/d/" . $insertedFile->getId() . "/edit' target='_blank'>" . $insertedFile->getTitle() . "</a>");
                }
//                }

            }
        }
        closeSession();
    }
}

function URSRC_calendar_create($loggin, $fileId, $loginid_name, $URSC_uld_id, $finaldate, $calenderid, $status, $form, $filesarray, $URSRC_firstname, $URSRC_lastname, $folderid)
{
    global $con, $ClientId, $ClientSecret, $RedirectUri, $DriveScopes, $CalenderScopes, $Refresh_Token;
    $drive = new Google_Client();
    $Client = get_servicedata();
    $ClientId = "651424197810-72ki9kr1k58v3qec0034q1bfj2og6ss8.apps.googleusercontent.com";
    //$Client[0];
    $ClientSecret = "NRY1PYuUK-NeJAZVJxUvXBeb";
    //$Client[1];
    $RedirectUri = "https://developers.google.com/oauthplayground";
    //$Client[2];
    $DriveScopes = "https://www.googleapis.com/auth/drive";
    //$Client[3];
    $CalenderScopes = "https://www.googleapis.com/auth/calendar";
    //$Client[4];
    $Refresh_Token = "1/YkIO518mEEVO9z5bdieivdpf9XVBnZN4PWZPLStyGzk";
    //$Client[5];
    $drive->setClientId($ClientId);
    $drive->setClientSecret($ClientSecret);
    $drive->setRedirectUri($RedirectUri);
    $drive->setScopes(array($DriveScopes, $CalenderScopes));
    $drive->setAccessType('online');
    $authUrl = $drive->createAuthUrl();
    $refresh_token = $Refresh_Token;
    $drive->refreshToken($refresh_token);
    $service = new Google_Service_Drive($drive);
    //    print_r($service);
    if ($form == 'TERMINATE') {
        $file_arraycount = 1;
        try {
            $permissions = $service->permissions->listPermissions($fileId);
            $return_value = $permissions->getItems();
        } catch (Exception $e) {
            $ss_flag = 0;
        }
        foreach ($return_value as $key => $value) {
            if ($value->emailAddress == $loggin) {
                $permission_id = $value->id;
            }
        }
        if ($permission_id != '') {
            try {
                $service->permissions->delete($fileId, $permission_id);
                $ss_flag = 1;
            } catch (Exception $e) {
                $ss_flag = 0;
            }
        } else {
            $ss_flag = 1;
        }
    } else {
        $value = $loggin;
        $type = 'user';
        $role = 'reader';
        $email = $loggin;
        $newPermission = new Google_Service_Drive_Permission();
        $newPermission->setValue($value);
        $newPermission->setType($type);
        $newPermission->setRole($role);
        $newPermission->setEmailAddress($email);
        try {
            $service->permissions->insert($fileId, $newPermission);
            $ss_flag = 1;
        } catch (Exception $e) {
            $ss_flag = 0;
        }
        if ($ss_flag == 1) {
            if ($filesarray != '') {
                $file_array = array();
                $allfilearray = explode(",", $filesarray);
                foreach ($allfilearray as $value) {
                    $uploadfilename = $value;
                    $drivefilename = $URSRC_firstname . ' ' . $URSRC_lastname . '-' . $uploadfilename;
                    $extension = explode(".", $uploadfilename);
                    if ($extension[1] == 'pdf') {
                        $mimeType = 'application/pdf';
                    }
                    if ($extension[1] == 'jpg') {
                        $mimeType = 'image/jpeg';
                    }
                    if ($extension[1] == 'png') {
                        $mimeType = 'image/png';
                    }
                    $file_id_value = insertFile($service, $drivefilename, 'PersonalDetails', $folderid, $mimeType, $uploadfilename);
                    if ($file_id_value != '') {
                        array_push($file_array, $file_id_value);
                    }
                }
                $file_arraycount = count($file_array);
            } else {
                $file_arraycount = 1;
            }
        }
    }
    if ($ss_flag == 1 && $file_arraycount > 0) {
        $cal = new Google_Service_Calendar($drive);
        $event = new Google_Service_Calendar_Event();
        $event->setsummary($loginid_name . '  ' . $status);
        $event->setDescription($URSC_uld_id);
        $start = new Google_Service_Calendar_EventDateTime();
        $start->setDate($finaldate);
        //setDate('2014-11-18');
        $event->setStart($start);
        $event->setEnd($start);
        try {
            $createdEvent = $cal->events->insert($calenderid, $event);
            $cal_flag = 1;
        } catch (Exception $e) {
            $cal_flag = 0;
        }
    }
    $flag_array = [$ss_flag, $cal_flag, $file_id_value, $file_array];
    return $flag_array;
}
Example #4
0
}
if (isset($_POST["baIDdel"]) && isset($_POST['count'])) {
    $explode = explode(',', $_POST["baIDdel"]);
    $count = intval($_POST['count']);
    for ($i = 0; $i < $count; $i++) {
        deleteBasketItem($explode[$i]);
    }
}
if (isset($_POST["prID"]) && isset($_POST["aPrice"]) && isset($_POST["EmpNum"])) {
    $res = addBasket($_POST);
}
if (isset($_POST["submit"])) {
    if (empty($_POST["title"]) || empty($_POST["point"]) || empty($_POST["Delivery"]) || empty($_POST["content"]) || empty($_FILES)) {
        $error_message = "<div class='error'>Please fill in all fields</div>";
    } else {
        $file_path = insertFile($_FILES, $_POST["menu_id"], $_POST["sub_id"]);
        if ($file_path != 'error') {
            $data = array('aTitle' => $_POST["title"], 'aPrice' => $_POST["point"], 'delivery' => $_POST["Delivery"], 'aContent' => $_POST["content"], 'menuID' => $_POST["menu_id"], 'subID' => $_POST["sub_id"], 'Image_name' => $file_path);
            insertProduct($data);
        }
    }
}
$basket = getBasket($_SESSION["user"]->EmpNum);
if (count($basket) > 0 && is_array($basket)) {
    $basket_isset = true;
} else {
    $basket_isset = false;
}
if (isset($_GET["menu_id"])) {
    $menu_id = $_GET["menu_id"];
    $menu = getMenuRows($menu_id);
Example #5
0
function getFilms(&$return, $paths = NULL)
{
    $error = "";
    $db = connectDB();
    if (!isset($paths)) {
        if (defined("PATHS")) {
            $paths = unserialize(PATHS);
        }
        return false;
    }
    foreach ($paths as $path) {
        $path = str_replace('\\', '/', $path . '/');
        //f*****g Windows
        $result = NULL;
        if (!listFile($result, $path)) {
            $error .= "Erreur sur l'ouverture du répértoire ('{$path}')\n";
            continue;
        }
        //récupération de l'id de la source ou son ajout si nécessaire
        if (($source_id = getSourceId($db, $path)) === false) {
            $source_id = insertSource($db, $path);
        }
        $return = array();
        foreach ($result as $row) {
            if (!getInfoOfFilm($row[RESULT_NAME], $title, $file_type)) {
                $error .= "Name is invalide " . $row[RESULT_NAME];
                continue;
            }
            //récupération de l'id du type de fichier
            if (($file_type_id = getTypeId($db, $file_type)) === false) {
                //PARANOIA use default type id : 1
                $file_type_id = 1;
            }
            $row[RESULT_PATH_CLEAR] = str_replace($path, "", $row[RESULT_PATH]);
            if (empty($row[RESULT_PATH_CLEAR])) {
                $row[RESULT_PATH_CLEAR] = ".";
            }
            //récupération de l'id de du fichier ou son ajout si nécessaire
            if (($file_id = getFile($db, $source_id, $row[RESULT_PATH_CLEAR], $row[RESULT_NAME], $file_type_id)) === false) {
                $file_id = insertFile($db, $source_id, $row[RESULT_PATH_CLEAR], $row[RESULT_NAME], $title, $file_type_id);
            }
            if ($title !== false) {
                // echo $error;
                $return[] = array($file_id, $title);
            } else {
                $error .= "Titre non trouvé pour le fichier ('{$row[RESULT_PATH]}{$row[RESULT_NAME]}')";
            }
        }
    }
    if (empty($return)) {
        return false;
    }
    return true;
}
Example #6
0
     $res["label"] = $_POST["nameSub"];
     updateSubImageAndName($res);
 }
 if (isset($_POST["submit"])) {
     $content = trim($_POST["content"]);
     if (empty($_POST["title"]) || empty($_POST["point"]) || empty($_POST["Delivery"]) || empty($content)) {
         $error_message = "<div class='error'>Please fill in all fields</div>";
     } else {
         if (isset($_POST["sub_id"])) {
             $sub_id_insert = $_POST["sub_id"];
         } else {
             $sub_id_insert = NULL;
         }
         $data = array('aTitle' => $_POST["title"], 'aPrice' => $_POST["point"], 'delivery' => $_POST["Delivery"], 'aContent' => $_POST["content"], 'showID' => $_POST["showID"], 'menuID' => $_POST["menu_id"], 'subID' => $sub_id_insert);
         if (!empty($_FILES["fileImage"]['name'])) {
             $file_path = insertFile($_POST["menu_id"], $sub_id_insert);
             $data['Image_name'] = $file_path;
         }
         if (isset($_POST["prID"])) {
             $data['prID'] = $_POST["prID"];
             if ($sub_id_insert == 'other') {
                 $data['subID'] = NULL;
             }
             updateProduct($data);
         } else {
             /*
             var_dump($_POST);
             echo "<br><br><br><br>";
             var_dump($data);
             */
             insertProduct($data);
             $ClientSecret = $Client[1];
             $RedirectUri = $Client[2];
             $DriveScopes = $Client[3];
             $CalenderScopes = $Client[4];
             $Refresh_Token = $Client[5];
             $drive->setClientId($ClientId);
             $drive->setClientSecret($ClientSecret);
             $drive->setRedirectUri($RedirectUri);
             $drive->setScopes(array($DriveScopes, $CalenderScopes));
             $drive->setAccessType('online');
             $authUrl = $drive->createAuthUrl();
             $access_token = $drive->getAccessToken();
             $refresh_token = $Refresh_Token;
             $drive->refreshToken($refresh_token);
             $service = new Google_Service_Drive($drive);
             $file_id_value = insertFile($service, $ufilename, 'PersonalDetails', $new_empfolderid, $ufiletype, $ufiletempname);
             if ($file_id_value != '') {
                 array_push($file_array, $file_id_value);
             }
         }
     }
 }
 if ($upload_flag == 1 && count($file_array) == 0) {
     $file_flag = 0;
     URSRC_unshare_document($loginid, $fileId);
     URSRC_unshare_document($loginid, $codeopti_fileId);
     $con->rollback();
     $login_empid = getEmpfolderName($loginid);
     renamefile($service, $login_empid, $new_empfolderid);
 }
 //UPDATE PART SENDING MAIL
Example #8
0
             mkdir("files");
         }
         $kvery = $kvery1 . $kvery2 . $kvery3;
         $kv = mysqli_query_wrapper($dblink, $kvery);
         if (!$kv) {
             echo "File export failed, trying SELECT with file output<br>";
             $kvery = $kvery1 . $kvery3;
             $kv = mysqli_query_wrapper($dblink, $kvery);
             $fexp = fopen("files/" . $tmpfile, "w");
             while ($erej = mysqli_fetch_array($kv, MYSQLI_ASSOC)) {
                 fwrite($fexp, $erej["hash"] . ($salted ? $config["fieldseparator"] . $erej["salt"] : "") . $config["fieldseparator"] . $erej["plaintext"] . "\n");
             }
             fclose($fexp);
         }
         if ($kv) {
             if (insertFile("files/" . $tmpfile)) {
                 echo "Cracked hashes from hashlist {$hlist} exported.";
             } else {
                 echo "Cracked hashes exported, but the file is missing.";
             }
         } else {
             echo "Could not export hashlist {$hlist}";
         }
     } else {
         echo "No such hashlist.";
     }
     break;
 case "hashes":
     // show hashes based on provided criteria
     $hlist = intval($_GET["hashlist"]);
     $chunk = intval($_GET["chunk"]);
Example #9
0
 public function createProject()
 {
     // project name sanitize
     $oldName = $this->projectStructure['project_name'];
     $this->projectStructure['project_name'] = $this->_sanitizeName($this->projectStructure['project_name']);
     if ($this->projectStructure['project_name'] == false) {
         $this->projectStructure['result']['errors'][] = array("code" => -5, "message" => "Invalid Project Name " . $oldName . ": it should only contain numbers and letters!");
         return false;
     }
     // create project
     $this->projectStructure['ppassword'] = $this->_generatePassword();
     $this->projectStructure['user_ip'] = Utils::getRealIpAddr();
     $this->projectStructure['id_customer'] = 'translated_user';
     $this->projectStructure['id_project'] = insertProject($this->projectStructure);
     //create user (Massidda 2013-01-24)
     //check if all the keys are valid MyMemory keys
     if (!empty($this->projectStructure['private_tm_key'])) {
         foreach ($this->projectStructure['private_tm_key'] as $i => $_tmKey) {
             $this->tmxServiceWrapper->setTmKey($_tmKey['key']);
             try {
                 $keyExists = $this->tmxServiceWrapper->checkCorrectKey();
                 if (!isset($keyExists) || $keyExists === false) {
                     Log::doLog(__METHOD__ . " -> TM key is not valid.");
                     throw new Exception("TM key is not valid.", -4);
                 }
             } catch (Exception $e) {
                 $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                 return false;
             }
             //set the first key as primary
             $this->tmxServiceWrapper->setTmKey($this->projectStructure['private_tm_key'][0]['key']);
         }
         //check if the MyMemory keys provided by the user are already associated to him.
         if ($this->projectStructure['userIsLogged']) {
             $mkDao = new TmKeyManagement_MemoryKeyDao($this->dbHandler);
             $searchMemoryKey = new TmKeyManagement_MemoryKeyStruct();
             $searchMemoryKey->uid = $this->projectStructure['uid'];
             $userMemoryKeys = $mkDao->read($searchMemoryKey);
             $userTmKeys = array();
             $memoryKeysToBeInserted = array();
             //extract user tm keys
             foreach ($userMemoryKeys as $_memoKey) {
                 /**
                  * @var $_memoKey TmKeyManagement_MemoryKeyStruct
                  */
                 $userTmKeys[] = $_memoKey->tm_key->key;
             }
             foreach ($this->projectStructure['private_tm_key'] as $_tmKey) {
                 if (!in_array($_tmKey['key'], $userTmKeys)) {
                     $newMemoryKey = new TmKeyManagement_MemoryKeyStruct();
                     $newTmKey = new TmKeyManagement_TmKeyStruct();
                     $newTmKey->key = $_tmKey['key'];
                     $newTmKey->tm = true;
                     $newTmKey->glos = true;
                     //TODO: take this from input
                     $newTmKey->name = $_tmKey['name'];
                     $newMemoryKey->tm_key = $newTmKey;
                     $newMemoryKey->uid = $this->projectStructure['uid'];
                     $memoryKeysToBeInserted[] = $newMemoryKey;
                 } else {
                     Log::doLog('skip insertion');
                 }
             }
             try {
                 $mkDao->createList($memoryKeysToBeInserted);
             } catch (Exception $e) {
                 Log::doLog($e->getMessage());
                 # Here we handle the error, displaying HTML, logging, ...
                 $output = "<pre>\n";
                 $output .= $e->getMessage() . "\n\t";
                 $output .= "</pre>";
                 Utils::sendErrMailReport($output);
             }
         }
         //the base case is when the user clicks on "generate private TM" button:
         //a (user, pass, key) tuple is generated and can be inserted
         //if it comes with it's own key without querying the creation API, create a (key,key,key) user
         if (empty($this->projectStructure['private_tm_user'])) {
             $this->projectStructure['private_tm_user'] = $this->projectStructure['private_tm_key'][0]['key'];
             $this->projectStructure['private_tm_pass'] = $this->projectStructure['private_tm_key'][0]['key'];
         }
         insertTranslator($this->projectStructure);
     }
     //sort files in order to process TMX first
     $sortedFiles = array();
     foreach ($this->projectStructure['array_files'] as $fileName) {
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             //found TMX, enable language checking routines
             $this->checkTMX = 1;
             array_unshift($sortedFiles, $fileName);
         } else {
             array_push($sortedFiles, $fileName);
         }
     }
     $this->projectStructure['array_files'] = $sortedFiles;
     unset($sortedFiles);
     $uploadDir = INIT::$UPLOAD_REPOSITORY . DIRECTORY_SEPARATOR . $this->projectStructure['uploadToken'];
     //fetch cache links, created by converter, from upload directory
     $linkFiles = scandir($uploadDir);
     //remove dir hardlinks, as uninteresting, as weel as regular files; only hash-links
     foreach ($linkFiles as $k => $linkFile) {
         if (strpos($linkFile, '.') !== false or strpos($linkFile, '|') === false) {
             unset($linkFiles[$k]);
         }
     }
     /*
        loop through all input files to
        1)upload TMX
        2)convert, in case, non standard XLIFF files to a format that Matecat understands
     
        Note that XLIFF that don't need conversion are moved anyway as they are to cache in order not to alter the workflow
     */
     foreach ($this->projectStructure['array_files'] as $fileName) {
         //if TMX,
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             //load it into MyMemory; we'll check later on how it went
             $file = new stdClass();
             $file->file_path = "{$uploadDir}/{$fileName}";
             $this->tmxServiceWrapper->setName($fileName);
             $this->tmxServiceWrapper->setFile(array($file));
             try {
                 $this->tmxServiceWrapper->addTmxInMyMemory();
             } catch (Exception $e) {
                 $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                 return false;
             }
             //in any case, skip the rest of the loop, go to the next file
             continue;
         }
         /*
           Conversion Enforce
           Checking Extension is no more sufficient, we want check content if this is an idiom xlf file type, conversion are enforced
           $enforcedConversion = true; //( if conversion is enabled )
         */
         $isAnXliffToConvert = $this->isConversionToEnforce($fileName);
         //we are going to access the storage, get model object to manipulate it
         $fs = new FilesStorage();
         //if it's one of the listed formats or conversion is not enabled in first place
         if (!$isAnXliffToConvert) {
             /*
               filename is already an xliff and it's in upload directory
               we have to make a cache package from it to avoid altering the original path
             */
             //get file
             $filePathName = "{$uploadDir}/{$fileName}";
             //calculate hash + add the fileName, if i load 3 equal files with the same content
             // they will be squashed to the last one
             $sha1 = sha1(file_get_contents($filePathName) . $filePathName);
             //make a cache package (with work/ only, emtpy orig/)
             $fs->makeCachePackage($sha1, $this->projectStructure['source_language'], false, $filePathName);
             //put reference to cache in upload dir to link cache to session
             $fs->linkSessionToCache($sha1, $this->projectStructure['source_language'], $this->projectStructure['uploadToken']);
             //add newly created link to list
             $linkFiles[] = $sha1 . "|" . $this->projectStructure['source_language'];
             unset($sha1);
         }
     }
     //now, upload dir contains only hash-links
     //we start copying files to "file" dir, inserting metadata in db and extracting segments
     foreach ($linkFiles as $linkFile) {
         //converted file is inside cache directory
         //get hash from file name inside UUID dir
         $hashFile = basename($linkFile);
         $hashFile = explode('|', $hashFile);
         //use hash and lang to fetch file from package
         $xliffFilePathName = $fs->getXliffFromCache($hashFile[0], $hashFile[1]);
         //get sha
         $sha1_original = $hashFile[0];
         //get original file name
         $originalFilePathName = $fs->getOriginalFromCache($hashFile[0], $hashFile[1]);
         $raw_originalFilePathName = explode(DIRECTORY_SEPARATOR, $originalFilePathName);
         $fileName = array_pop($raw_originalFilePathName);
         unset($hashFile);
         if (!file_exists($xliffFilePathName)) {
             $this->projectStructure['result']['errors'][] = array("code" => -6, "message" => "File not found on server after upload.");
         }
         try {
             $info = pathinfo($xliffFilePathName);
             if (!in_array($info['extension'], array('xliff', 'sdlxliff', 'xlf'))) {
                 throw new Exception("Failed to find Xliff - no segments found", -3);
             }
             $mimeType = pathinfo($fileName, PATHINFO_EXTENSION);
             $yearMonthPath = date_create()->format("Ymd");
             $fileDateSha1Path = $yearMonthPath . DIRECTORY_SEPARATOR . $sha1_original;
             $fid = insertFile($this->projectStructure, $fileName, $mimeType, $fileDateSha1Path);
             //move the file in the right directory from the packages to the file dir
             $fs->moveFromCacheToFileDir($fileDateSha1Path, $this->projectStructure['source_language'], $fid);
             $this->projectStructure['file_id_list']->append($fid);
             $this->_extractSegments(file_get_contents($xliffFilePathName), $fid);
         } catch (Exception $e) {
             if ($e->getCode() == -1) {
                 $this->projectStructure['result']['errors'][] = array("code" => -1, "message" => "No text to translate in the file {$fileName}.");
                 $fs->deleteHashFromUploadDir($uploadDir, $linkFile);
             } elseif ($e->getCode() == -2) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store segments in database for {$fileName}");
             } elseif ($e->getCode() == -3) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "File {$fileName} not found. Failed to save XLIFF conversion on disk");
             } elseif ($e->getCode() == -4) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Internal Error. Xliff Import: Error parsing. ( {$fileName} )");
             } elseif ($e->getCode() == -11) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files on disk. Permission denied");
             } elseif ($e->getCode() == -12) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files in database");
             } elseif ($e->getCode() == -13) {
                 $this->projectStructure['result']['errors'][] = array("code" => -13, "message" => $e->getMessage());
                 Log::doLog($e->getMessage());
                 return null;
                 // SEVERE EXCEPTION we can not write to disk!! Break project creation
             } else {
                 //mysql insert Blob Error
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to create project. Database Error on {$fileName}. Please try again.");
             }
             Log::doLog($e->getMessage());
         }
     }
     //end of hash-link loop
     //check if the files language equals the source language. If not, set an error message.
     if (!$this->projectStructure['skip_lang_validation']) {
         $this->validateFilesLanguages();
     }
     /****************/
     //loop again through files to check to check for TMX loading
     foreach ($this->projectStructure['array_files'] as $fileName) {
         //if TMX,
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             $this->tmxServiceWrapper->setName($fileName);
             $result = array();
             //is the TM loaded?
             //wait until current TMX is loaded
             while (true) {
                 try {
                     $result = $this->tmxServiceWrapper->tmxUploadStatus();
                     if ($result['completed']) {
                         //"$fileName" has been loaded into MyMemory"
                         //exit the loop
                         break;
                     }
                     //"waiting for "$fileName" to be loaded into MyMemory"
                     sleep(3);
                 } catch (Exception $e) {
                     $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                     Log::doLog($e->getMessage() . "\n" . $e->getTraceAsString());
                     //exit project creation
                     return false;
                 }
             }
             //once the language is loaded, check if language is compliant (unless something useful has already been found)
             if (1 == $this->checkTMX) {
                 //get localized target languages of TM (in case it's a multilingual TM)
                 $tmTargets = explode(';', $result['data']['target_lang']);
                 //indicates if something has been found for current memory
                 $found = false;
                 //compare localized target languages array (in case it's a multilingual project) to the TM supplied
                 //if nothing matches, then the TM supplied can't have matches for this project
                 //create an empty var and add the source language too
                 $project_languages = array_merge((array) $this->projectStructure['target_language'], (array) $this->projectStructure['source_language']);
                 foreach ($project_languages as $projectTarget) {
                     if (in_array($this->langService->getLocalizedName($projectTarget), $tmTargets)) {
                         $found = true;
                         break;
                     }
                 }
                 //if this TM matches the project lagpair and something has been found
                 if ($found and $result['data']['source_lang'] == $this->langService->getLocalizedName($this->projectStructure['source_language'])) {
                     //the TMX is good to go
                     $this->checkTMX = 0;
                 } elseif ($found and $result['data']['target_lang'] == $this->langService->getLocalizedName($this->projectStructure['source_language'])) {
                     /*
                      * This means that the TMX has a srclang as specification in the header. Warn the user.
                      * Ex:
                      * <header creationtool="SDL Language Platform"
                      *      creationtoolversion="8.0"
                      *      datatype="rtf"
                      *      segtype="sentence"
                      *      adminlang="DE-DE"
                      *      srclang="DE-DE" />
                      */
                     $this->projectStructure['result']['errors'][] = array("code" => -16, "message" => "The TMX you provided explicitly specifies {$result['data']['source_lang']} as source language. Check that the specified language source in the TMX file match the language source of your project or remove that specification in TMX file.");
                     $this->checkTMX = 0;
                     Log::doLog($this->projectStructure['result']);
                 }
             }
         }
     }
     if (1 == $this->checkTMX) {
         //this means that noone of uploaded TMX were usable for this project. Warn the user.
         $this->projectStructure['result']['errors'][] = array("code" => -16, "message" => "The TMX did not contain any usable segment. Check that the languages in the TMX file match the languages of your project.");
         Log::doLog($this->projectStructure['result']);
         return false;
     }
     if (!empty($this->projectStructure['result']['errors'])) {
         Log::doLog("Project Creation Failed. Sent to Output all errors.");
         Log::doLog($this->projectStructure['result']['errors']);
         return false;
     }
     //Log::doLog( array_pop( array_chunk( $SegmentTranslations[$fid], 25, true ) ) );
     //create job
     if (isset($_SESSION['cid']) and !empty($_SESSION['cid'])) {
         $owner = $_SESSION['cid'];
     } else {
         $_SESSION['_anonym_pid'] = $this->projectStructure['id_project'];
         //default user
         $owner = '';
     }
     $isEmptyProject = false;
     //Throws exception
     try {
         $this->_createJobs($this->projectStructure, $owner);
         //FIXME for project with pre translation this query is not enough,
         //we need compare the number of segments with translations, but take an eye to the opensource
         $query_visible_segments = "SELECT count(*) as cattool_segments\n\t\t\t\tFROM segments WHERE id_file IN ( %s ) and show_in_cattool = 1";
         $string_file_list = implode(",", $this->projectStructure['file_id_list']->getArrayCopy());
         $query_visible_segments = sprintf($query_visible_segments, $string_file_list);
         $rows = $this->dbHandler->fetch_array($query_visible_segments);
         if (!$rows) {
             Log::doLog("Segment Search: Failed Retrieve min_segment/max_segment for files ( {$string_file_list} ) - DB Error: " . var_export($this->dbHandler->get_error(), true) . " - \n");
             throw new Exception("Segment Search: Failed Retrieve min_segment/max_segment for job", -5);
         }
         if ($rows[0]['cattool_segments'] == 0) {
             Log::doLog("Segment Search: No segments in this project - \n");
             $isEmptyProject = true;
         }
     } catch (Exception $ex) {
         $this->projectStructure['result']['errors'][] = array("code" => -9, "message" => "Fail to create Job. ( {$ex->getMessage()} )");
         return false;
     }
     try {
         Utils::deleteDir($uploadDir);
         if (is_dir($uploadDir . '_converted')) {
             Utils::deleteDir($uploadDir . '_converted');
         }
     } catch (Exception $e) {
         $output = "<pre>\n";
         $output .= " - Exception: " . print_r($e->getMessage(), true) . "\n";
         $output .= " - REQUEST URI: " . print_r(@$_SERVER['REQUEST_URI'], true) . "\n";
         $output .= " - REQUEST Message: " . print_r($_REQUEST, true) . "\n";
         $output .= " - Trace: \n" . print_r($e->getTraceAsString(), true) . "\n";
         $output .= "\n\t";
         $output .= "Aborting...\n";
         $output .= "</pre>";
         Log::doLog($output);
         Utils::sendErrMailReport($output, $e->getMessage());
     }
     $this->projectStructure['status'] = INIT::$VOLUME_ANALYSIS_ENABLED ? Constants_ProjectStatus::STATUS_NEW : Constants_ProjectStatus::STATUS_NOT_TO_ANALYZE;
     if ($isEmptyProject) {
         $this->projectStructure['status'] = Constants_ProjectStatus::STATUS_EMPTY;
     }
     $this->projectStructure['result']['code'] = 1;
     $this->projectStructure['result']['data'] = "OK";
     $this->projectStructure['result']['ppassword'] = $this->projectStructure['ppassword'];
     $this->projectStructure['result']['password'] = $this->projectStructure['array_jobs']['job_pass'];
     $this->projectStructure['result']['id_job'] = $this->projectStructure['array_jobs']['job_list'];
     $this->projectStructure['result']['job_segments'] = $this->projectStructure['array_jobs']['job_segments'];
     $this->projectStructure['result']['id_project'] = $this->projectStructure['id_project'];
     $this->projectStructure['result']['project_name'] = $this->projectStructure['project_name'];
     $this->projectStructure['result']['source_language'] = $this->projectStructure['source_language'];
     $this->projectStructure['result']['target_language'] = $this->projectStructure['target_language'];
     $this->projectStructure['result']['status'] = $this->projectStructure['status'];
     $this->projectStructure['result']['lang_detect'] = $this->projectStructure['lang_detect_files'];
     $query_project_summary = "\n            SELECT\n                 COUNT( s.id ) AS project_segments,\n                 SUM( IF( IFNULL( st.eq_word_count, -1 ) = -1, s.raw_word_count, st.eq_word_count ) ) AS project_raw_wordcount\n            FROM segments s\n            INNER JOIN files_job fj ON fj.id_file = s.id_file\n            INNER JOIN jobs j ON j.id= fj.id_job\n            LEFT JOIN segment_translations st ON s.id = st.id_segment\n            WHERE j.id_project = %u\n        ";
     $query_project_summary = sprintf($query_project_summary, $this->projectStructure['id_project']);
     $project_summary = $this->dbHandler->fetch_array($query_project_summary);
     $update_project_count = "\n            UPDATE projects\n              SET\n                standard_analysis_wc = %.2F,\n                status_analysis = '%s'\n            WHERE id = %u\n        ";
     $update_project_count = sprintf($update_project_count, $project_summary[0]['project_raw_wordcount'], $this->projectStructure['status'], $this->projectStructure['id_project']);
     $this->dbHandler->query($update_project_count);
     //        Log::doLog( $this->projectStructure );
     //create Project into DQF queue
     if (INIT::$DQF_ENABLED && !empty($this->projectStructure['dqf_key'])) {
         $dqfProjectStruct = DQF_DqfProjectStruct::getStruct();
         $dqfProjectStruct->api_key = $this->projectStructure['dqf_key'];
         $dqfProjectStruct->project_id = $this->projectStructure['id_project'];
         $dqfProjectStruct->name = $this->projectStructure['project_name'];
         $dqfProjectStruct->source_language = $this->projectStructure['source_language'];
         $dqfQueue = new Analysis_DqfQueueHandler();
         try {
             $dqfQueue->createProject($dqfProjectStruct);
             //for each job, push a task into AMQ's DQF queue
             foreach ($this->projectStructure['array_jobs']['job_list'] as $i => $jobID) {
                 /**
                  * @var $dqfTaskStruct DQF_DqfTaskStruct
                  */
                 $dqfTaskStruct = DQF_DqfTaskStruct::getStruct();
                 $dqfTaskStruct->api_key = $this->projectStructure['dqf_key'];
                 $dqfTaskStruct->project_id = $this->projectStructure['id_project'];
                 $dqfTaskStruct->task_id = $jobID;
                 $dqfTaskStruct->target_language = $this->projectStructure['target_language'][$i];
                 $dqfTaskStruct->file_name = uniqid('', true) . $this->projectStructure['project_name'];
                 $dqfQueue->createTask($dqfTaskStruct);
             }
         } catch (Exception $exn) {
             $output = __METHOD__ . " (code " . $exn->getCode() . " ) - " . $exn->getMessage();
             Log::doLog($output);
             Utils::sendErrMailReport($output, $exn->getMessage());
         }
     }
 }
Example #10
0
 /**
  * @ Function Name	: managefolder
  * @ Function Params	: 
  * @ Function Purpose 	: sends mail to all user from admin side.
  * @ Function Returns	: 
  */
 public function managefolder($id = null)
 {
     isAdminAuthorize();
     /* checked is admin login or not */
     $this->load->model('adminmodel');
     if ($id) {
         $data['title'] = 'Edit folder';
     } else {
         $data['title'] = 'New folder';
     }
     $data['foder_array'] = $this->adminmodel->getallfolders($id, null);
     if (isset($id) && $id != '') {
         //$data['folderDetail']=$this->adminmodel->getallfolders($id,'getbyId'); comment on 2709
         @($data['folderDetail']['parentfolder'] = $this->adminmodel->getallfolders($id, 'byuserId'));
     }
     //pre($data['folderDetail']);
     $options = walk_dir_folder(0, "", $id, 'option');
     //pre($options);
     //echo "<select>";
     //$options;
     //echo "</select>";
     if (count($options) > 0) {
         $data['userfoldersoption'] = $options;
     }
     //pre($data['parentfolder']);
     if ($this->input->post('btnsubmit')) {
         $result_row = $this->adminmodel->getallfolders($this->input->post('parentfolderid'), 'getbyId');
         $clientid = $result_row[0]['userId'];
         $folderLevel = $result_row[0]['folderLevel'];
         //pr($result_row);
         $clientInfoArry = $this->adminmodel->getclientDetail($clientid);
         //pr($clientInfoArry);
         /* setredirect url folder id */
         if ($this->input->post('redirectfolderid') != null) {
             $this->session->set_userdata('redirecturlfolderid', $this->input->post('redirectfolderid'));
         }
         if ($this->input->post('id')) {
             $this->form_validation->set_rules('folderName', 'Name', 'required');
         } else {
             $this->form_validation->set_rules('parentfolderid', 'folder name', 'required');
             $this->form_validation->set_rules('folderName', 'Name', 'required|callback_valid_unique_folder');
         }
         if ($this->form_validation->run() == false) {
             $this->load->view('admin/managefolder.php', $data);
             //return false;
         } else {
             if ($this->input->post('id') != null) {
                 $folderArray = array('folderName' => $this->input->post('folderName'), 'id' => $this->input->post('id'));
             } else {
                 $folderArray = array('folderName' => $this->input->post('folderName'), 'parentId' => $this->input->post('parentfolderid'), 'userId' => $clientid, 'googleFolderName' => $this->input->post('folderName'), 'id' => $this->input->post('id'), 'folderLevel' => $folderLevel + 1);
             }
             /* save data array in sesssion */
             $this->session->set_userdata('folderArrayset', $folderArray);
             /* Verify google client */
             $resultArray = $this->adminmodel->getAccesrefreshToken($clientInfoArry['email']);
             //pr($resultArray);
             if (empty($resultArray['refreshToken'])) {
                 redirect('admin/managefolder');
             }
             $refreshtoken = $resultArray['refreshToken'];
             $accessToken = $this->get_admin_google_accesstoken($refreshtoken);
             if (!empty($accessToken)) {
                 $this->google_client->setAccessToken($accessToken);
             } else {
                 redirect('admin/managefolder');
             }
             $folderparentid = $this->session->userdata('folderArrayset');
             $parent_folder_row = $this->adminmodel->getallfolders($folderparentid['parentId'], 'getbyId');
             $parentfolderName = $parent_folder_row[0]['googleFolderName'];
             $redirectfolderid = $parent_folder_row[0]['userId'];
             $folderArray = $this->session->userdata('folderArrayset');
             try {
                 $client = $this->google_client;
                 $service = new Google_DriveService($client);
                 if ($folderArray['id'] == null) {
                     //pr($parentfolderName);
                     /* Search parent folder in google drive */
                     $this->data['user_folders_list'] = retrieveAllFiles($service);
                     //pr($this->data['user_folders_list']);
                     foreach ($this->data['user_folders_list'] as $folders) {
                         if ($folders->title == $parentfolderName) {
                             //pr($parentfolderName);
                             /* Create a folder */
                             $description = 'new folder in' . $folderArray['folderName'];
                             $parentId = $folders->id;
                             $mimeType = "application/vnd.google-apps.folder";
                             $filename = $folderArray['folderName'];
                             $return = insertFile($service, $folderArray['folderName'], $description, $parentId, $mimeType, $filename);
                         }
                     }
                 }
                 if ($return) {
                     $folderArray = array_merge($folderArray, array('googlefolderId' => $return->id));
                     $result = $this->adminmodel->savefolder($folderArray);
                 }
                 if ($result && $return) {
                     if ($result == 'update') {
                         echo $this->session->set_flashdata('message', '<div class="alert-success">Folder updated successfully.</div>');
                     } else {
                         echo $this->session->set_flashdata('message', '<div class="alert-success">Folder added successfully.</div>');
                     }
                 } else {
                     echo $this->session->set_flashdata('message', '<div class="alert-error">Folder not added, please try again.</div>');
                 }
             } catch (Exception $e) {
                 pr($e);
                 $this->session->set_flashdata('message', '<div class="alert-error">' . $this->lang->line('google_client_not_valid_email') . '</div>');
             }
             redirect('admin/folderlist/' . $this->session->userdata('redirecturlfolderid'));
         }
     } else {
         $this->load->view('admin/managefolder.php', $data);
     }
 }
Example #11
0
function insertCourse($code, $name, $semester, $year, $instructor_id, $department_id)
{
    checkConnectivity();
    $query = sprintf("insert into course(code,name,semster,year,instructor_id,department_id) values('%s','%s','%s','%s',%s,%s)", $code, $name, $semester, $year, $instructor_id, $department_id);
    mysqli_query($GLOBALS['connection_link'], $query);
    //  each course should have 6 files initially
    $fileTypes = array("Course_Specifications", "Materials_&_Labs", "Assignments_&_Project_Documents", "Midterm_Exam", "Final_Exam", "End_of_Course_Report");
    $i = 0;
    $id = mysqli_insert_id($GLOBALS['connection_link']);
    $result = mysqli_affected_rows($GLOBALS['connection_link']);
    for ($i; $i < 6; $i++) {
        insertFile($fileTypes[$i], $id);
    }
    return $result > 0;
}
Example #12
0
 //create project
 $pid = insertProject('translated_user', "uploadFile");
 print "project: " . $pid . "\n";
 //create pass
 $length = 8;
 // Random
 $pool = "abcdefghkmnpqrstuvwxyz23456789";
 // skipping iljo01 because not easy to distinguish
 $pool_lenght = strlen($pool);
 $pwd = "";
 for ($index = 0; $index < $length; $index++) {
     $pwd .= substr($pool, rand() % $pool_lenght, 1);
 }
 //create job and file
 $jid = insertJob($pwd, $pid, '', $xml->Languages->attributes()->source, $xml->Languages->attributes()->target, '', '');
 $fid = insertFile($pid, $fileName, $xml->Languages->attributes()->source, 'xml', 'uploaded');
 insertFilesJob($jid, $fid);
 print "job_id: " . $jid . "\n";
 print "file_id: " . $fid . "\n";
 //get translations
 $initials = [];
 $count = 0;
 //initial translations
 for ($i = 0; $i < count($xml->initialTargetText->children()); $i++) {
     $id = $xml->initialTargetText->segment[$i]->attributes()->id;
     $suggestion = $xml->initialTargetText->segment[$i];
     $initials[$count] = [$id, $suggestion];
     $count = $count + 1;
 }
 $translations = [];
 $count = 0;
Example #13
0
function scanPHP(&$paths, $db, $printStatus = false)
{
    foreach ($paths as $key => $value) {
        if ($value['ext'] == 'php') {
            $path = $value['path'];
            if (insertFile($db, $path)) {
                cleanElement($db, $path);
                if ($printStatus) {
                    echo "SCAN " . $path . PHP_EOL;
                }
                $path_parts = pathinfo($path);
                insertElement($db, $path, $path_parts['filename'], $path_parts['extension'], "", 'file', 0);
                $content = file_get_contents($path);
                $tokens = token_get_all($content);
                /*if($path  == '/var/www/src/grep/test.php')
                       	{
                        	echo "<pre>";
                        	var_dump($tokens);
                			echo "</pre>";
                		}*/
                $tree = array();
                scanTree($tree, $tokens, 0);
                /*if($path  == '/var/www/src/grep/test.php')
                       	{
                			echo "<pre>";
                        	var_dump($tree);
                			echo "</pre>";
                		}*/
                saveTree($tree, $tokens, $path, $db);
            } else {
                if ($printStatus) {
                    echo "SKIP " . $path . PHP_EOL;
                }
            }
        }
    }
}
function commandCheck($command)
{
    global $servername, $username, $password;
    // Swicth case checking input argument
    switch ($command[1]) {
        case "--help":
            helpDirectives();
            break;
        case "--file":
            $filename = $command[2];
            if ($command[3] == "-u") {
                $username = $command[4];
            } elseif ($command[3] == "-p") {
                $password = $command[4];
            } elseif ($command[3] == "-h") {
                $servername = $command[4];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[5] == "-u") {
                $username = $command[6];
            } elseif ($command[5] == "-p") {
                $password = $command[6];
            } elseif ($command[5] == "-h") {
                $servername = $command[6];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[7] == "-u") {
                $username = $command[8];
            } elseif ($command[7] == "-p") {
                $password = $command[8];
            } elseif ($command[7] == "-h") {
                $servername = $command[8];
            } else {
                exit("Invalid user or host argument\n");
            }
            initDB();
            insertFile($filename);
            break;
        case "--create_table":
            if ($command[2] == "-u") {
                $username = $command[3];
            } elseif ($command[2] == "-p") {
                $password = $command[3];
            } elseif ($command[2] == "-h") {
                $servername = $command[3];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[4] == "-u") {
                $username = $command[5];
            } elseif ($command[4] == "-p") {
                $password = $command[5];
            } elseif ($command[4] == "-h") {
                $servername = $command[5];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[6] == "-u") {
                $username = $command[7];
            } elseif ($command[6] == "-p") {
                $password = $command[7];
            } elseif ($command[6] == "-h") {
                $servername = $command[7];
            } else {
                exit("Invalid user or host argument\n");
            }
            initDB();
            createTable();
            break;
        case "--dry_run":
            $filename = $command[3];
            if ($command[4] == "-u") {
                $username = $command[5];
            } elseif ($command[4] == "-p") {
                $password = $command[5];
            } elseif ($command[4] == "-h") {
                $servername = $command[5];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[6] == "-u") {
                $username = $command[7];
            } elseif ($command[6] == "-p") {
                $password = $command[7];
            } elseif ($command[6] == "-h") {
                $servername = $command[7];
            } else {
                exit("Invalid user or host argument\n");
            }
            if ($command[8] == "-u") {
                $username = $command[9];
            } elseif ($command[8] == "-p") {
                $password = $command[9];
            } elseif ($command[8] == "-h") {
                $servername = $command[9];
            } else {
                exit("Invalid user or host argument\n");
            }
            initDB();
            dryRun($filename);
            break;
        default:
            echo "Invalid command entered\n";
    }
}
function URSRC_calendar_create($loggin,$fileId,$loginid_name,$URSC_uld_id,$finaldate,$calenderid,$status,$form,$filesarray,$URSRC_firstname,$URSRC_lastname,$folderid){
    global $con,$ClientId,$ClientSecret,$RedirectUri,$DriveScopes,$CalenderScopes,$Refresh_Token;
    $drive = new Google_Client();
    $drive->setClientId($ClientId);
    $drive->setClientSecret($ClientSecret);
    $drive->setRedirectUri($RedirectUri);
    $drive->setScopes(array($DriveScopes,$CalenderScopes));
    $drive->setAccessType('online');
    $authUrl = $drive->createAuthUrl();
    $refresh_token= $Refresh_Token;
    $drive->refreshToken($refresh_token);
    $service = new Google_Service_Drive($drive);
    if($form=='TERMINATE'){
        $file_arraycount=1;
        try {
            $permissions = $service->permissions->listPermissions($fileId);
            $return_value= $permissions->getItems();
        } catch (Exception $e) {
            $ss_flag=0;
        }
        foreach ($return_value as $key => $value) {
            if ($value->emailAddress==$loggin) {
                $permission_id=$value->id;
            }
        }
        if($permission_id!=''){
            try {
                $service->permissions->delete($fileId, $permission_id);
                $ss_flag=1;
            } catch (Exception $e) {
                $ss_flag=0;
            }
        }
        else{

            $ss_flag=1;
        }
    }
    else{
        $value=$loggin;
        $type='user';
        $role='reader';
        $email=$loggin;
        $newPermission = new Google_Service_Drive_Permission();
        $newPermission->setValue($value);
        $newPermission->setType($type);
        $newPermission->setRole($role);
        $newPermission->setEmailAddress($email);
        try {
            $service->permissions->insert($fileId, $newPermission);
            $ss_flag=1;
        } catch (Exception $e) {
            $ss_flag=0;
        }

        if($ss_flag==1){
            if($filesarray!='')
            {
                $file_array=array();
                $allfilearray=(explode(",",$filesarray));
                foreach ($allfilearray as $value)
                {
                    $uploadfilename=$value;
                    $drivefilename=$URSRC_firstname.' '.$URSRC_lastname.'-'.$uploadfilename;
                    $extension =(explode(".",$uploadfilename));
                    if($extension[1]=='pdf'){$mimeType='application/pdf';}
                    if($extension[1]=='jpg'){$mimeType='image/jpeg';}
                    if($extension[1]=='png'){$mimeType='image/png';}
                    $file_id_value =insertFile($service,$drivefilename,'PersonalDetails',$folderid,$mimeType,$uploadfilename);
                    if($file_id_value!=''){
                        array_push($file_array,$file_id_value);
                    }
                }
                $file_arraycount=count($file_array);
            }
            else{
                $file_arraycount=1;
            }
        }


    }
    if($ss_flag==1 && $file_arraycount>0){
        $cal = new Google_Service_Calendar($drive);
        $event = new Google_Service_Calendar_Event();
        $event->setsummary($loginid_name.'  '.$status);
        $event->setDescription($URSC_uld_id);
        $start = new Google_Service_Calendar_EventDateTime();
        $start->setDate($finaldate);//setDate('2014-11-18');
        $event->setStart($start);
        $event->setEnd($start);
        try{
            $createdEvent = $cal->events->insert($calenderid, $event);
            $cal_flag=1;
        }
        catch(Exception $e){
            $cal_flag=0;
        }
    }
    $flag_array=[$ss_flag,$cal_flag,$file_id_value,$file_array];
    return $flag_array;
}
Example #16
0
function save_custom_meta($post_id)
{
    global $custom_meta_fields, $post;
    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    $files = getFileByPostID($post->ID);
    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        if ($field['type'] == 'tax_select') {
            continue;
        }
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
        if ($field['type'] == 'download') {
            $gID = $_POST['_infomation_download_file_id_'];
            $files = (array) $files;
            foreach ($files as $file) {
                $file = (array) $file;
                if (!in_array($file['file_id'], $gID)) {
                    deleteFile(array('file_id' => $file['file_id']));
                }
            }
            $gFileName = $_POST['_infomation_download_file_name_'];
            $gFileLink = $_POST['_infomation_download_file_'];
            $gFileDes = $_POST['_infomation_download_des_'];
            for ($i = 0; $i < count($gID); $i++) {
                if (!empty($gFileName[$i]) && !empty($gFileLink[$i])) {
                    if (empty($gID[$i])) {
                        $data = array('post_id' => $post_id, 'file' => $gFileLink[$i], 'jad_file' => " ", 'file_name' => $gFileName[$i], 'file_des' => $gFileDes[$i], 'file_size' => remote_filesize($gFileLink[$i]), 'file_date' => date("d-m-Y H:i:s"), 'file_updated_date' => date("d-m-Y H:i:s"), 'file_last_downloaded_date' => date("d-m-Y H:i:s"));
                        insertFile($data);
                    } else {
                        $data = array('post_id' => $post_id, 'file' => $gFileLink[$i], 'jad_file' => " ", 'file_name' => $gFileName[$i], 'file_des' => $gFileDes[$i], 'file_size' => remote_filesize($gFileLink[$i]), 'file_updated_date' => date("d-m-Y H:i:s"));
                        $where = array('file_id' => $gID[$i]);
                        updateFile($data, $where);
                    }
                }
            }
        }
    }
    // enf foreach
}
Example #17
0
function insertFile($filePath)
{
    include 'openDB.php';
    $key = hash('sha256', $filePath);
    $user = $_SESSION['user'];
    $insert = $db->prepare("insert into files (file, key, users) values ('{$filePath}', '{$key}', '{$user}')");
    $insert->execute();
    include 'closeDB.php';
}
session_start();
if (isset($_SESSION['user']) && isset($_POST['dir'])) {
    include 'config.php';
    include 'auth.php';
    $uploadDir = getDir($_POST['dir']);
    if (!auth('dir', $_SESSION['user'], $uploadDir)) {
        header('Location: /logout.php');
    }
    $errors = array();
    $file_name = $_FILES['uploadFile']['name'];
    $file_size = $_FILES['uploadFile']['size'];
    $file_tmp = $_FILES['uploadFile']['tmp_name'];
    $file_type = $_FILES['uploadFile']['type'];
    if ($file_size > $maxUploadSize) {
        $errors[] = "File is too large";
    }
    if (empty($errors) == true) {
        move_uploaded_file($file_tmp, $uploadDir . $file_name);
        insertFile($uploadDir . $file_name);
    }
}
header("Location: /files.php");
Example #18
0
// Refresh the user token and grand the privileges
$client->setAccessToken($credentials);
$service = new Google_Service_Drive($client);
// Set the file metadata for drive
$mimeType = $_FILES["file"]["type"];
$title = $_FILES["file"]["name"];
$description = "Uploaded from your very first google drive application!";
// Get the folder metadata
if (!empty($_POST["folderName"])) {
    $folderName = $_POST["folderName"];
}
if (!empty($_POST["folderDesc"])) {
    $folderDesc = $_POST["folderDesc"];
}
// Call the insert function with parameters listed below
$driveInfo = insertFile($service, $title, $description, $mimeType, $file_tmp_name, $folderName, $folderDesc);
/**
* Get the folder ID if it exists, if it doesnt exist, create it and return the ID
*
* @param Google_DriveService $service Drive API service instance.
* @param String $folderName Name of the folder you want to search or create
* @param String $folderDesc Description metadata for Drive about the folder (optional)
* @return Google_Drivefile that was created or got. Returns NULL if an API error occured
*/
function getFolderExistsCreate($service, $folderName, $folderDesc)
{
    // List all user files (and folders) at Drive root
    $files = $service->files->listFiles();
    $found = false;
    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
Example #19
0
function formProcess_file($option)
{
    $errorText = '';
    if (!check_csrf_token()) {
        zamgerlog("csrf token nije dobar", 3);
        zamgerlog2("csrf token nije dobar");
        return "Poslani podaci nisu ispravni. Vratite se nazad, ponovo popunite formu i kliknite na dugme Pošalji";
    }
    set_time_limit(0);
    if (!in_array($option, array('add', 'edit'))) {
        $errorText = 'Doslo je do greske prilikom spasavanja podataka. Molimo kontaktirajte administratora.';
        return $errorText;
    }
    $id = intval($_REQUEST['id']);
    if ($option == 'edit' && $id <= 0) {
        $errorText = 'Doslo je do greske prilikom spasavanja podataka. Molimo kontaktirajte administratora.';
        zamgerlog("pokusao urediti nepostojeci fajl {$id}, projekat {$projekat} (pp{$predmet})", 3);
        zamgerlog2("pokusao urediti nepostojeci fajl", $id, $projekat);
        return $errorText;
    }
    if ($option == 'edit' && isThisFileFirstRevision($id) == false) {
        //cannot get access to revisions other than the first one
        $errorText = 'Doslo je do greske prilikom spasavanja podataka. Molimo kontaktirajte administratora.';
        zamgerlog("pokusao urediti staru reviziju fajla {$id}, projekat {$projekat} (pp{$predmet})", 3);
        zamgerlog2("pokusao urediti staru reviziju fajla", $id, $projekat);
        return $errorText;
    }
    //process file
    if ($option == 'edit') {
        $entry = getFileFirstRevision($id);
        $lastRevisionEntry = getFileLastRevision($id);
    }
    //get variables
    $filename = $_FILES['filename'];
    if ($option == 'edit') {
        $revizija = $lastRevisionEntry[revizija] + 1;
        $file = $entry['id'];
    } else {
        $revizija = 1;
        $file = '';
    }
    $projekat = intval($_REQUEST['projekat']);
    $predmet = intval($_REQUEST['predmet']);
    global $userid;
    if ($filename['error'] == 4) {
        $errorText = 'Unesite sva obavezna polja.';
        return $errorText;
    }
    global $conf_files_path;
    $lokacijafajlova = "{$conf_files_path}/projekti/fajlovi/{$projekat}/{$userid}/";
    if (!file_exists("{$conf_files_path}/projekti/fajlovi/{$projekat}")) {
        mkdir("{$conf_files_path}/projekti/fajlovi/{$projekat}", 0777, true);
    }
    if (!file_exists($lokacijafajlova)) {
        mkdir($lokacijafajlova, 0777, true);
    }
    //adding or replacing file - depends on the $option parameter(add, edit)
    if ($filename['error'] > 0) {
        if ($filename['error'] == 1 || $filename['error'] == 2) {
            $errorText .= 'Pokušavate poslati fajl koji je veci od dozvoljene velicine. Probajte sa manjim fajlom.<br />';
        } else {
            $errorText .= 'Vaš fajl nije poslan korektno. Molimo pokušajte ponovo.<br />';
        }
        return $errorText;
    } else {
        //No error occured so far
        //escape file name before upload
        if ($option == 'add') {
            $Name = $filename['name'];
        } else {
            $Name = $entry[filename];
        }
        $Name = trim($Name);
        //make directory structure for this file
        //$uploadDir = $lokacijafajlova . "$Name" . "_revizije/v$revizija/";
        $uploadDir = $lokacijafajlova . "{$Name}/";
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $uploadDir = $uploadDir . "v{$revizija}/";
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        //final file name
        if ($option == 'add') {
            $uploadFile = $Name;
        } else {
            $uploadFile = $entry['filename'];
        }
        if (move_uploaded_file($filename['tmp_name'], $uploadDir . $uploadFile)) {
            //transfered a file to upload directory from temp dir
            //if edit option REPLACING the old image (overwrite)
            chmod($uploadDir . $uploadFile, 0777);
        } else {
            $errorText .= 'Desila se greška prilikom uploada fajla. Molimo kontaktirajte administratora.<br />AA';
            return $errorText;
        }
        //else
    }
    //else
    //diff
    $diff = '';
    $diffing = 0;
    if ($option == 'edit') {
        //diffing with textual files only
        $lastRevisionFile = $lokacijafajlova . $lastRevisionEntry['filename'] . '/v' . $lastRevisionEntry['revizija'] . '/' . $lastRevisionEntry['filename'];
        $newFile = $uploadDir . $uploadFile;
        $extension = preg_replace('/.+(\\..*)$/', '$1', $lastRevisionEntry['filename']);
        $textExtensions = array('.txt');
        if (in_array($extension, $textExtensions)) {
            $diffing = 1;
        }
        if ($diffing == 1) {
            $diff = `/usr/bin/diff -u {$lastRevisionFile} {$newFile}`;
        }
    }
    //option == edit
    $data = array('filename' => $uploadFile, 'revizija' => $revizija, 'file' => $file, 'osoba' => $userid, 'projekat' => $projekat, 'diffing' => $diffing, 'diff' => $diff);
    if (!insertFile($data)) {
        $errorText = 'Doslo je do greske prilikom spasavanja podataka. Molimo kontaktirajte administratora.';
        return $errorText;
    }
    return $errorText;
}
 public function doAction()
 {
     if (empty($this->file_name)) {
         $this->result['errors'][] = array("code" => -1, "message" => "Missing file name.");
         return false;
     }
     $arFiles = explode(',', $this->file_name);
     $default_project_name = $arFiles[0];
     if (count($arFiles) > 1 && empty($this->project_name)) {
         $default_project_name = "MATECAT_PROJ-" . date("Ymdhi");
     }
     $intDir = INIT::$UPLOAD_ROOT . '/' . $_COOKIE['upload_session'];
     if (count($arFiles) > 0) {
         $xliff = simplexml_load_file($intDir . '/' . $arFiles[0]);
         $src_lang = (string) $xliff->file['source-language'];
         if (!empty($src_lang) && empty($this->source_language)) {
             $this->source_language = $src_lang;
         }
         $tgt_lang = (string) $xliff->file['target-language'];
         if (!empty($tgt_lang) && empty($this->target_language)) {
             $this->target_language = $tgt_lang;
         }
     }
     if (empty($this->project_name)) {
         $this->project_name = $default_project_name;
         //'NO_NAME'.$this->create_project_name();
     }
     if (empty($this->source_language)) {
         $this->result['errors'][] = array("code" => -3, "message" => "Missing source language.");
         return false;
     }
     if (empty($this->target_language)) {
         $this->result['errors'][] = array("code" => -4, "message" => "Missing target language.");
         return false;
     }
     if (empty($this->tms_engine)) {
         $this->tms_engine = 1;
         // default MyMemory
     }
     // add her the cookie mangement for remembere the last 3 choosed languages
     // project name sanitize
     $this->project_name = preg_replace('/["\' \\(\\)\\[\\]\\{\\}\\+\\*]/', "_", $this->project_name);
     $this->project_name = preg_replace('/[_]{2,}/', "_", $this->project_name);
     $this->project_name = STR_replace('_.', ".", $this->project_name);
     //echo $this->project_name;
     // project name validation
     $pattern = "/^[\\p{L}\\ 0-9a-zA-Z_\\.\\-]+\$/";
     if (!preg_match($pattern, $this->project_name)) {
         $this->result['errors'][] = array("code" => -5, "message" => "Invalid Project Name {$this->project_name}: it should only contain numbers and letters!");
         //	        $this->result['project_name_error'] = $this->project_name;
         return false;
     }
     // create project
     $pid = insertProject('translated_user', $this->project_name);
     //create job
     $password = $this->create_password();
     $jid = insertJob($password, $pid, '', $this->source_language, $this->target_language, $this->mt_engine, $this->tms_engine);
     foreach ($arFiles as $file) {
         $filename = $intDir . '/' . $file;
         if (file_exists($filename)) {
         } else {
             $this->result['errors'][] = array("code" => -6, "message" => "File not found on server after upload.");
         }
         $handle = fopen($filename, "r");
         $contents = fread($handle, filesize($filename));
         fclose($handle);
         $fileSplit = explode('.', $file);
         $mimeType = $fileSplit[count($fileSplit) - 1];
         $fid = insertFile($pid, $file, $this->source_language, $mimeType, $contents);
         insertFilesJob($jid, $fid);
         $insertSegments = extractSegments($intDir, $file, $pid, $fid, $jid);
     }
     $this->deleteDir($intDir);
     if ($insertSegments) {
         $this->result['code'] = 1;
         $this->result['data'] = "OK";
         $this->result['password'] = $password;
         $this->result['id_job'] = $jid;
         $this->result['project_name'] = $this->project_name;
         $this->result['source_language'] = $this->source_language;
         $this->result['target_language'] = $this->target_language;
     } else {
         $this->result['errors'][] = array("code" => -7, "message" => "Not able to import this XLIFF file. ({$file})");
     }
     setcookie("upload_session", "", time() - 10000);
 }
Example #21
0
 function upload_file_to_google_drive($title, $filename)
 {
     $fileId = searchFile($this->service, $title);
     if ($fileId != null) {
         echo __FUNCTION__ . ": updating file: " . $filename . " to google drive\n";
         updateFile($this->service, $fileId, $title, $title, $this->mime_type, $filename, false);
     } else {
         echo __FUNCTION__ . ": uploading file: " . $filename . " to google drive\n";
         insertFile($this->service, $title, $title, $this->folder_id, $this->mime_type, $filename);
     }
 }
Example #22
0
 public function createProject()
 {
     // project name sanitize
     $oldName = $this->projectStructure['project_name'];
     $this->projectStructure['project_name'] = $this->_sanitizeName($this->projectStructure['project_name']);
     if ($this->projectStructure['project_name'] == false) {
         $this->projectStructure['result']['errors'][] = array("code" => -5, "message" => "Invalid Project Name " . $oldName . ": it should only contain numbers and letters!");
         return false;
     }
     // create project
     $this->projectStructure['ppassword'] = $this->_generatePassword();
     $this->projectStructure['user_ip'] = Utils::getRealIpAddr();
     $this->projectStructure['id_customer'] = 'translated_user';
     $this->projectStructure['id_project'] = insertProject($this->projectStructure);
     //create user (Massidda 2013-01-24)
     //check if all the keys are valid MyMemory keys
     if (!empty($this->projectStructure['private_tm_key'])) {
         foreach ($this->projectStructure['private_tm_key'] as $i => $_tmKey) {
             $this->tmxServiceWrapper->setTmKey($_tmKey['key']);
             try {
                 $keyExists = $this->tmxServiceWrapper->checkCorrectKey();
                 if (!isset($keyExists) || $keyExists === false) {
                     Log::doLog(__METHOD__ . " -> TM key is not valid.");
                     throw new Exception("TM key is not valid.", -4);
                 }
             } catch (Exception $e) {
                 $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                 return false;
             }
             //set the first key as primary
             $this->tmxServiceWrapper->setTmKey($this->projectStructure['private_tm_key'][0]['key']);
         }
         //check if the MyMemory keys provided by the user are already associated to him.
         if ($this->projectStructure['userIsLogged']) {
             $mkDao = new TmKeyManagement_MemoryKeyDao($this->dbHandler);
             $searchMemoryKey = new TmKeyManagement_MemoryKeyStruct();
             $searchMemoryKey->uid = $this->projectStructure['uid'];
             $userMemoryKeys = $mkDao->read($searchMemoryKey);
             $userTmKeys = array();
             $memoryKeysToBeInserted = array();
             //extract user tm keys
             foreach ($userMemoryKeys as $_memoKey) {
                 /**
                  * @var $_memoKey TmKeyManagement_MemoryKeyStruct
                  */
                 $userTmKeys[] = $_memoKey->tm_key->key;
             }
             foreach ($this->projectStructure['private_tm_key'] as $_tmKey) {
                 if (!in_array($_tmKey['key'], $userTmKeys)) {
                     $newMemoryKey = new TmKeyManagement_MemoryKeyStruct();
                     $newTmKey = new TmKeyManagement_TmKeyStruct();
                     $newTmKey->key = $_tmKey['key'];
                     $newTmKey->tm = true;
                     $newTmKey->glos = true;
                     //TODO: take this from input
                     $newTmKey->name = $_tmKey['name'];
                     $newMemoryKey->tm_key = $newTmKey;
                     $newMemoryKey->uid = $this->projectStructure['uid'];
                     $memoryKeysToBeInserted[] = $newMemoryKey;
                 } else {
                     Log::doLog('skip insertion');
                 }
             }
             try {
                 $mkDao->createList($memoryKeysToBeInserted);
             } catch (Exception $e) {
                 Log::doLog($e->getMessage());
                 # Here we handle the error, displaying HTML, logging, ...
                 $output = "<pre>\n";
                 $output .= $e->getMessage() . "\n\t";
                 $output .= "</pre>";
                 Utils::sendErrMailReport($output);
             }
         }
         //the base case is when the user clicks on "generate private TM" button:
         //a (user, pass, key) tuple is generated and can be inserted
         //if it comes with it's own key without querying the creation API, create a (key,key,key) user
         if (empty($this->projectStructure['private_tm_user'])) {
             $this->projectStructure['private_tm_user'] = $this->projectStructure['private_tm_key'][0]['key'];
             $this->projectStructure['private_tm_pass'] = $this->projectStructure['private_tm_key'][0]['key'];
         }
         insertTranslator($this->projectStructure);
     }
     //sort files in order to process TMX first
     $sortedFiles = array();
     foreach ($this->projectStructure['array_files'] as $fileName) {
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             //found TMX, enable language checking routines
             $this->checkTMX = 1;
             array_unshift($sortedFiles, $fileName);
         } else {
             array_push($sortedFiles, $fileName);
         }
     }
     $this->projectStructure['array_files'] = $sortedFiles;
     unset($sortedFiles);
     $uploadDir = INIT::$UPLOAD_REPOSITORY . DIRECTORY_SEPARATOR . $this->projectStructure['uploadToken'];
     foreach ($this->projectStructure['array_files'] as $fileName) {
         //if TMX,
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             $file = new stdClass();
             $file->file_path = "{$uploadDir}/{$fileName}";
             $this->tmxServiceWrapper->setName($fileName);
             $this->tmxServiceWrapper->setFile(array($file));
             try {
                 $this->tmxServiceWrapper->addTmxInMyMemory();
             } catch (Exception $e) {
                 $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                 return false;
             }
             //in any case, skip the rest of the loop, go to the next file
             continue;
         }
         /**
          * Conversion Enforce
          *
          * we have to know if a file can be found in _converted directory
          *
          * Check Extension no more sufficient, we want check content
          * if this is an idiom xlf file type, conversion are enforced
          * $enforcedConversion = true; //( if conversion is enabled )
          */
         $isAConvertedFile = true;
         try {
             $fileType = DetectProprietaryXliff::getInfo(INIT::$UPLOAD_REPOSITORY . DIRECTORY_SEPARATOR . $this->projectStructure['uploadToken'] . DIRECTORY_SEPARATOR . $fileName);
             if (DetectProprietaryXliff::isXliffExtension()) {
                 if (INIT::$CONVERSION_ENABLED) {
                     //conversion enforce
                     if (!INIT::$FORCE_XLIFF_CONVERSION) {
                         //ONLY IDIOM is forced to be converted
                         //if file is not proprietary like idiom AND Enforce is disabled
                         //we take it as is
                         if (!$fileType['proprietary']) {
                             $isAConvertedFile = false;
                             //ok don't convert a standard sdlxliff
                         }
                     } else {
                         //if conversion enforce is active
                         //we force all xliff files but not files produced by SDL Studio because we can handle them
                         if ($fileType['proprietary_short_name'] == 'trados') {
                             $isAConvertedFile = false;
                             //ok don't convert a standard sdlxliff
                         }
                     }
                 } elseif ($fileType['proprietary']) {
                     /**
                      * Application misconfiguration.
                      * upload should not be happened, but if we are here, raise an error.
                      * @see upload.class.php
                      * */
                     $this->projectStructure['result']['errors'][] = array("code" => -8, "message" => "Proprietary xlf format detected. Not able to import this XLIFF file. ({$fileName})");
                     setcookie("upload_session", "", time() - 10000);
                     return -1;
                     //stop execution
                 } elseif (!$fileType['proprietary']) {
                     $isAConvertedFile = false;
                     //ok don't convert a standard sdlxliff
                 }
             }
         } catch (Exception $e) {
             Log::doLog($e->getMessage());
         }
         $mimeType = pathinfo($fileName, PATHINFO_EXTENSION);
         $original_content = "";
         /*
           if it's not one of the listed formats (or it is, but you had to convert it anyway), 
           and conversion is enabled in first place
         */
         if ($isAConvertedFile) {
             //converted file is inside "_converted" directory
             $fileDir = $uploadDir . '_converted';
             $original_content = file_get_contents("{$uploadDir}/{$fileName}");
             $sha1_original = sha1($original_content);
             $original_content = gzdeflate($original_content, 5);
             //file name is a xliff converted like: 'a_word_document.doc.sdlxliff'
             $real_fileName = $fileName . '.sdlxliff';
         } else {
             //filename is already an xliff and it is in a canonical normal directory
             $sha1_original = "";
             $fileDir = $uploadDir;
             $real_fileName = $fileName;
         }
         $filePathName = $fileDir . DIRECTORY_SEPARATOR . $real_fileName;
         if (!file_exists($filePathName)) {
             $this->projectStructure['result']['errors'][] = array("code" => -6, "message" => "File not found on server after upload.");
         }
         try {
             $info = pathinfo($filePathName);
             if ($info['extension'] == 'xliff' || $info['extension'] == 'sdlxliff' || $info['extension'] == 'xlf') {
                 $contents = file_get_contents($filePathName);
             } else {
                 throw new Exception("Failed to find Xliff - no segments found", -3);
             }
             $fid = insertFile($this->projectStructure, $fileName, $mimeType, $contents, $sha1_original, $original_content);
             $this->projectStructure['file_id_list']->append($fid);
             $this->_extractSegments($contents, $fid);
             unset($contents);
             //free memory
             //Log::doLog( $this->projectStructure['segments'] );
         } catch (Exception $e) {
             if ($e->getCode() == -1) {
                 $this->projectStructure['result']['errors'][] = array("code" => -1, "message" => "No text to translate in the file {$fileName}.");
             } elseif ($e->getCode() == -2) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store segments in database for {$fileName}");
             } elseif ($e->getCode() == -3) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "File {$fileName} not found. Failed to save XLIFF conversion on disk");
             } elseif ($e->getCode() == -4) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Internal Error. Xliff Import: Error parsing. ( {$fileName} )");
             } elseif ($e->getCode() == -11) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files on disk. Permission denied");
             } elseif ($e->getCode() == -12) {
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "Failed to store reference files in database");
             } else {
                 //mysql insert Blob Error
                 $this->projectStructure['result']['errors'][] = array("code" => -7, "message" => "File is Too large. ( {$fileName} )");
             }
             Log::doLog($e->getMessage());
         }
         //exit;
     }
     //check if the files language equals the source language. If not, set an error message.
     if (!$this->projectStructure['skip_lang_validation']) {
         $this->validateFilesLanguages();
     }
     /****************/
     //loop again through files to check to check for TMX loading
     foreach ($this->projectStructure['array_files'] as $fileName) {
         //if TMX,
         if ('tmx' == pathinfo($fileName, PATHINFO_EXTENSION)) {
             $this->tmxServiceWrapper->setName($fileName);
             $result = array();
             //is the TM loaded?
             //wait until current TMX is loaded
             while (true) {
                 try {
                     $result = $this->tmxServiceWrapper->tmxUploadStatus();
                     if ($result['completed']) {
                         //"$fileName" has been loaded into MyMemory"
                         //exit the loop
                         break;
                     }
                     //"waiting for "$fileName" to be loaded into MyMemory"
                     sleep(3);
                 } catch (Exception $e) {
                     $this->projectStructure['result']['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage());
                     Log::doLog($e->getMessage() . "\n" . $e->getTraceAsString());
                     //exit project creation
                     return false;
                 }
             }
             //once the language is loaded, check if language is compliant (unless something useful has already been found)
             if (1 == $this->checkTMX) {
                 //get localized target languages of TM (in case it's a multilingual TM)
                 $tmTargets = explode(';', $result['data']['target_lang']);
                 //indicates if something has been found for current memory
                 $found = false;
                 //compare localized target languages array (in case it's a multilingual project) to the TM supplied
                 //if nothing matches, then the TM supplied can't have matches for this project
                 //create an empty var and add the source language too
                 $project_languages = array_merge((array) $this->projectStructure['target_language'], (array) $this->projectStructure['source_language']);
                 foreach ($project_languages as $projectTarget) {
                     if (in_array($this->langService->getLocalizedName($projectTarget), $tmTargets)) {
                         $found = true;
                         break;
                     }
                 }
                 //if this TM matches the project lagpair and something has been found
                 if ($found and $result['data']['source_lang'] == $this->langService->getLocalizedName($this->projectStructure['source_language'])) {
                     //the TMX is good to go
                     $this->checkTMX = 0;
                 } elseif ($found and $result['data']['target_lang'] == $this->langService->getLocalizedName($this->projectStructure['source_language'])) {
                     /*
                      * This means that the TMX has a srclang as specification in the header. Warn the user.
                      * Ex:
                      * <header creationtool="SDL Language Platform"
                      *      creationtoolversion="8.0"
                      *      datatype="rtf"
                      *      segtype="sentence"
                      *      adminlang="DE-DE"
                      *      srclang="DE-DE" />
                      */
                     $this->projectStructure['result']['errors'][] = array("code" => -16, "message" => "The TMX you provided explicitly specifies {$result['data']['source_lang']} as source language. Check that the specified language source in the TMX file match the language source of your project or remove that specification in TMX file.");
                     $this->checkTMX = 0;
                     Log::doLog($this->projectStructure['result']);
                 }
             }
         }
     }
     if (1 == $this->checkTMX) {
         //this means that noone of uploaded TMX were usable for this project. Warn the user.
         $this->projectStructure['result']['errors'][] = array("code" => -16, "message" => "The TMX did not contain any usable segment. Check that the languages in the TMX file match the languages of your project.");
         Log::doLog($this->projectStructure['result']);
         return false;
     }
     if (!empty($this->projectStructure['result']['errors'])) {
         Log::doLog("Project Creation Failed. Sent to Output all errors.");
         Log::doLog($this->projectStructure['result']['errors']);
         return false;
     }
     //Log::doLog( array_pop( array_chunk( $SegmentTranslations[$fid], 25, true ) ) );
     //create job
     if (isset($_SESSION['cid']) and !empty($_SESSION['cid'])) {
         $owner = $_SESSION['cid'];
     } else {
         $_SESSION['_anonym_pid'] = $this->projectStructure['id_project'];
         //default user
         $owner = '';
     }
     $isEmptyProject = false;
     //Throws exception
     try {
         $this->_createJobs($this->projectStructure, $owner);
         //FIXME for project with pre translation this query is not enough,
         //we need compare the number of segments with translations, but take an eye to the opensource
         $query_visible_segments = "SELECT count(*) as cattool_segments\n                FROM segments WHERE id_file IN ( %s ) and show_in_cattool = 1";
         $string_file_list = implode(",", $this->projectStructure['file_id_list']->getArrayCopy());
         $query_visible_segments = sprintf($query_visible_segments, $string_file_list);
         $rows = $this->dbHandler->fetch_array($query_visible_segments);
         if (!$rows) {
             Log::doLog("Segment Search: Failed Retrieve min_segment/max_segment for files ( {$string_file_list} ) - DB Error: " . var_export($this->dbHandler->get_error(), true) . " - \n");
             throw new Exception("Segment Search: Failed Retrieve min_segment/max_segment for job", -5);
         }
         if ($rows[0]['cattool_segments'] == 0) {
             Log::doLog("Segment Search: No segments in this project - \n");
             $isEmptyProject = true;
         }
     } catch (Exception $ex) {
         $this->projectStructure['result']['errors'][] = array("code" => -9, "message" => "Fail to create Job. ( {$ex->getMessage()} )");
         return false;
     }
     try {
         Utils::deleteDir($uploadDir);
         if (is_dir($uploadDir . '_converted')) {
             Utils::deleteDir($uploadDir . '_converted');
         }
     } catch (Exception $e) {
         $output = "<pre>\n";
         $output .= " - Exception: " . print_r($e->getMessage(), true) . "\n";
         $output .= " - REQUEST URI: " . print_r(@$_SERVER['REQUEST_URI'], true) . "\n";
         $output .= " - REQUEST Message: " . print_r($_REQUEST, true) . "\n";
         $output .= " - Trace: \n" . print_r($e->getTraceAsString(), true) . "\n";
         $output .= "\n\t";
         $output .= "Aborting...\n";
         $output .= "</pre>";
         Log::doLog($output);
         Utils::sendErrMailReport($output, $e->getMessage());
     }
     $this->projectStructure['status'] = INIT::$VOLUME_ANALYSIS_ENABLED ? Constants_ProjectStatus::STATUS_NEW : Constants_ProjectStatus::STATUS_NOT_TO_ANALYZE;
     if ($isEmptyProject) {
         $this->projectStructure['status'] = Constants_ProjectStatus::STATUS_EMPTY;
     }
     $this->projectStructure['result']['code'] = 1;
     $this->projectStructure['result']['data'] = "OK";
     $this->projectStructure['result']['ppassword'] = $this->projectStructure['ppassword'];
     $this->projectStructure['result']['password'] = $this->projectStructure['array_jobs']['job_pass'];
     $this->projectStructure['result']['id_job'] = $this->projectStructure['array_jobs']['job_list'];
     $this->projectStructure['result']['job_segments'] = $this->projectStructure['array_jobs']['job_segments'];
     $this->projectStructure['result']['id_project'] = $this->projectStructure['id_project'];
     $this->projectStructure['result']['project_name'] = $this->projectStructure['project_name'];
     $this->projectStructure['result']['source_language'] = $this->projectStructure['source_language'];
     $this->projectStructure['result']['target_language'] = $this->projectStructure['target_language'];
     $this->projectStructure['result']['status'] = $this->projectStructure['status'];
     $this->projectStructure['result']['lang_detect'] = $this->projectStructure['lang_detect_files'];
     $query_project_summary = "\n            SELECT\n                 COUNT( s.id ) AS project_segments,\n                 SUM( IF( IFNULL( st.eq_word_count, -1 ) = -1, s.raw_word_count, st.eq_word_count ) ) AS project_raw_wordcount\n            FROM segments s\n            INNER JOIN files_job fj ON fj.id_file = s.id_file\n            INNER JOIN jobs j ON j.id= fj.id_job\n            LEFT JOIN segment_translations st ON s.id = st.id_segment\n            WHERE j.id_project = %u\n        ";
     $query_project_summary = sprintf($query_project_summary, $this->projectStructure['id_project']);
     $project_summary = $this->dbHandler->fetch_array($query_project_summary);
     /**
      * TODO: remove after queue implementation
      */
     //        if( 0 && $project_summary[0]['project_segments'] > 50000 ) {
     //            $this->projectStructure[ 'status' ] = Constants_ProjectStatus::STATUS_NOT_TO_ANALYZE;
     //
     //            $msg = "
     //        WARNING: a project with more than 50.000 segments was created. ( " . $project_summary[0]['project_segments'] . " )\n" .
     //        var_export( $this->projectStructure[ 'result' ], true ) . "\n\n" .
     //                    "  " .
     //        var_export( $project_summary[0] , true ) . "\n";
     //
     //            Utils::sendErrMailReport( $msg, "Alert: Project Creation Abort. - " );
     //
     //        }
     $update_project_count = "\n            UPDATE projects\n              SET\n                standard_analysis_wc = %.2F,\n                status_analysis = '%s'\n            WHERE id = %u\n        ";
     $update_project_count = sprintf($update_project_count, $project_summary[0]['project_raw_wordcount'], $this->projectStructure['status'], $this->projectStructure['id_project']);
     $this->dbHandler->query($update_project_count);
     //        Log::doLog( $this->projectStructure );
     //create Project into DQF queue
     if (INIT::$DQF_ENABLED && !empty($this->projectStructure['dqf_key'])) {
         $dqfProjectStruct = DQF_DqfProjectStruct::getStruct();
         $dqfProjectStruct->api_key = $this->projectStructure['dqf_key'];
         $dqfProjectStruct->project_id = $this->projectStructure['id_project'];
         $dqfProjectStruct->name = $this->projectStructure['project_name'];
         $dqfProjectStruct->source_language = $this->projectStructure['source_language'];
         $dqfQueue = new Analysis_DqfQueueHandler();
         try {
             $dqfQueue->createProject($dqfProjectStruct);
             //for each job, push a task into AMQ's DQF queue
             foreach ($this->projectStructure['array_jobs']['job_list'] as $i => $jobID) {
                 /**
                  * @var $dqfTaskStruct DQF_DqfTaskStruct
                  */
                 $dqfTaskStruct = DQF_DqfTaskStruct::getStruct();
                 $dqfTaskStruct->api_key = $this->projectStructure['dqf_key'];
                 $dqfTaskStruct->project_id = $this->projectStructure['id_project'];
                 $dqfTaskStruct->task_id = $jobID;
                 $dqfTaskStruct->target_language = $this->projectStructure['target_language'][$i];
                 $dqfTaskStruct->file_name = uniqid('', true) . $this->projectStructure['project_name'];
                 $dqfQueue->createTask($dqfTaskStruct);
             }
         } catch (Exception $exn) {
             $output = __METHOD__ . " (code " . $exn->getCode() . " ) - " . $exn->getMessage();
             Log::doLog($output);
             Utils::sendErrMailReport($output, $exn->getMessage());
         }
     }
     //    var_dump($this->projectStructure);
     //        exit;
 }
Example #23
0
 public function checkfolderIsexistorNot()
 {
     $clientid = $this->session->userdata('clientId');
     if (empty($clientid)) {
         return false;
     }
     $allfolders = $this->usermodel->getallfolders($clientid, null);
     $checkcomp = false;
     if (count($allfolders) > 0) {
         $allfolders[0]['googlefolderId'];
         try {
             $client = $this->google_client;
             $client->setAccessToken($this->session->userdata('accessToken'));
             $service = new Google_DriveService($client);
             //pre($allfolders );
             foreach ($allfolders as $folder) {
                 try {
                     $file = $service->files->get($folder['googlefolderId']);
                 } catch (Exception $e) {
                     $file = '';
                 }
                 if ($file->labels->trashed == 1 || empty($file)) {
                     //pr($file);
                     $parentfolder = $this->usermodel->getallfolders($folder['parentId'], 'parentId');
                     $parentId = $parentfolder[0]['googlefolderId'];
                     /* Create a folder */
                     $description = 'new folder in' . $folder['folderName'];
                     $mimeType = "application/vnd.google-apps.folder";
                     $filename = $folder['folderName'];
                     $title = $folder['folderName'];
                     $return = insertFile($service, $title, $description, $parentId, $mimeType, $filename);
                     $googlefolderid = $return->id;
                     $this->usermodel->updategooglefolderkey($folder['id'], $googlefolderid);
                 }
             }
             $checkcomp = true;
         } catch (Exception $e) {
         }
     }
     if ($checkcomp) {
         $this->session->set_userdata('checkFold', true);
         //$uid=$this->session->userdata('userId');
         //$this->usermodel->textcode($uid);
     }
 }