| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458 |
- <?php
- /**
- * by plabudda 2013-10-09:
- *
- * 1. install:
- * - create *.plist file:
- * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
- * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
- * - load by launchctl:
- * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
- *
- * 2. uninstall:
- * - unload from launchctl:
- * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
- *
- * 3. debug:
- * - debug by www:
- * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
- * - more verbose debug:
- * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
- * - task:
- * /SE/se-dev-pl/bash_sync_perms.php?task=task
- * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
- * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
- * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
- *
- *
- * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
- * 'WAITING' - Kandydaci
- * 'NORMAL' - Aktywni pracownicy
- * 'DELETED' - Wyłączone konta
- * 'OFF_SOFT' - ?
- * 'OFF_HARD' - ?
- *
- * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
- * robienie katalogow dla korespondencji przy migracji na nowy typ pism
- #read PASSWORD
- #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
- #do
- #echo mkdir $a
- #mkdir $a
- #done
- *do wywolania w katalogach IN/OUT:
- # cd IN
- # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
- *
- *
- *
- * DONE: koresp format: PISMA/ID/...
- * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
- * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
- * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
- * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
- * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
- *
- *
- * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
- *
- * 5. Sync custom tables
- * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
- * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
- * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
- * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
- */
- ini_set('max_execution_time', 300);
- ini_set('memory_limit', '512M');
- define('DS', DIRECTORY_SEPARATOR);
- define('APP_PATH_ROOT', dirname(__FILE__));
- define('APP_PATH_WWW', dirname(__FILE__));
- define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
- // set ini to log errors into error log file
- ini_set('display_startup_errors', '0');
- ini_set('log_errors', '1');
- ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
- require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
- Lib::loadClass('V');
- Lib::loadClass('Config');
- Lib::loadClass('DB');
- Lib::loadClass('User');
- Lib::loadClass('FoldersConfig');
- Lib::loadClass('FileUploader');
- if (isset($_SERVER["argv"][1])) {
- $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
- $info = array();
- $info['max_execution_time'] = ini_get('max_execution_time');
- $info['memory_limit'] = ini_get('memory_limit');
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
- ini_set('max_execution_time', 300);
- ini_set('memory_limit', '512M');
- $info = array();
- $info['max_execution_time'] = ini_get('max_execution_time');
- $info['memory_limit'] = ini_get('memory_limit');
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
- SyncPerms::run(null, null, 'users', null);
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
- SyncPerms::run(null, null, 'usersAll', null);
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
- SyncPerms::run(null, null, 'nextTask', null);
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
- SyncPerms::run(null, null, 'newFiles', null);
- }
- else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
- $cmd = " ls -Rlea . ";
- exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
- //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
- $filesWithPermsTree = array();
- $lastName = '';
- $folderParent = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
- $lastName = '..';
- continue;
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- } else {
- // fix file name from bad chars
- // [8] => CV_Kowalski Mariusz`.pdf
- // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
- // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
- // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
- // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
- //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
- //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
- }
- echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
- $file->name = end($fileParts);
- $file->path = array();
- if ($folderParent) $file->path[] = $folderParent;
- $file->path[] = end($fileParts);
- $file->path = implode('/', $file->path);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
- $folderParent = substr($line, 2, -1);
- }
- else if (substr($line, 0, 5) == 'total') {
- continue;
- }
- else if (empty($line)) {
- $folderParent = '';
- continue;
- }
- }
- echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
- }
- else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
- SyncPerms::run(null, null);
- }
- else {
- die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
- }
- if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
- $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
- $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
- SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
- }
- class SyncPerms {
- public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
- if ($arg2 == 'addToLaunchctl') self::task__addToLaunchctl($domain);
- else if ($arg2 == 'newFiles') self::task__newFiles();
- else if ($arg2 == 'nextTask') self::task__nextTask();
- else if ($arg2 == 'testErrorLog') self::task__testErrorLog();
- else if ($arg2 == 'users') self::usersAction();
- else if ($arg2 == 'usersAll') self::usersAllAction();
- else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
- else if ($arg2 == 'sendNotify') self::sendNotify();
- else self::task__default();
- }
- public static function task__addToLaunchctl($domain) {
- $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
- system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
- <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
- <plist version=\"1.0\">
- <dict>
- <key>Disabled</key>
- <false/>
- <key>Label</key>
- <string>pl.biallnet.sync_perms.{$domain}.php</string>
- <key>UserName</key>
- <string>root</string>
- <key>ProgramArguments</key>
- <array>
- <string>php</string>
- <string>{$_SERVER["argv"][0]}</string>
- <string>{$_SERVER["argv"][1]}</string>
- </array>
- <key>StartInterval</key>
- <integer>60</integer>
- </dict>
- </plist>
- \" > {$plistFile}");
- echo "Run as root: launchctl load {$plistFile} \n";
- }
- public static function task__newFiles() {
- $time = new stdClass();
- $time->start = time();
- self::newFilesAction();
- $time->end = time();
- // TODO: print operation time if DBG
- }
- public static function task__nextTask() {
- $time = new stdClass();
- $time->start = time();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
- self::installTable();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
- self::generateTasksNewRecords();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
- self::generateTasksUpdated();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
- $limit = V::get('_limit', 1, $_GET, 'int');
- for ($i = 0; $i < $limit; $i++) {
- $time->cur = time();
- if ($time->cur - $time->start > 60 * 5) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
- break;
- }
- $task = self::nextTaskAction();
- if (!$task) break;
- }
- }
- public static function task__testErrorLog() {
- echo "display_errors: " . ini_get("display_errors") . "\n";
- echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
- echo "log_errors: " . ini_get("log_errors") . "\n";
- echo "error_reporting: " . ini_get("error_reporting") . "\n";
- echo "error_log: " . ini_get("error_log") . "\n";
- trigger_error("Notice: Test Error Log", E_USER_NOTICE);
- }
- public static function task__SyncPermsCustomTables() {
- $DBG_TIME = true;
- $dbgTime = new stdClass();
- $dbgTime->startTime = microtime(true);
- $dbgTime->lastTime = $dbgTime->startTime;
- $customSync = new SyncPermsCustomTables();
- // TODO: $customSync->run();
- $customSync->fetchConfig();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $customSync->installTable();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $rowId = (int)$arg3;
- if ($rowId > 0) {
- $customSync->executeTask('DEALS_TABLE', $rowId);// TODO: DEALS_TABLE ?
- }
- else {
- $customSync->generateTasksNewRecords();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $customSync->generateTasksUpdated();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $customSync->newFilesAction();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $limit = 1000;
- for ($i = 0; $i < $limit; $i++) {
- $loopTasksFired = 0;
- foreach ($customSync->_tbls as $tblName => $tblConf) {
- $task = $customSync->nextTaskAction($tblName);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if (!$task) {
- // TODO: rm $tblName from config to prevent searching for task in next loops
- unset($customSync->_tbls[$tblName]);
- continue;
- }
- $loopTasksFired++;
- }
- if (!$loopTasksFired) {
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- break;
- }
- $i += $loopTasksFired;
- }
- }
- $dbgTime->endTime = microtime(true);
- trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
- }
- public static function task__default() {
- $DBG_TIME = false;
- $DBG_MEMORY = false;
- $dbgTime = new stdClass();
- $dbgTime->start = time();
- $dbgTime->startTime = microtime(true);
- $dbgTime->lastTime = $dbgTime->startTime;
- self::installTable();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- self::generateTasksNewRecords();
- if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- self::generateTasksUpdated();
- if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $dbgTime->cur = time();
- if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
- trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
- return;
- }
- self::newFilesAction();
- if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $limit = 100;
- for ($i = 0; $i < $limit; $i++) {
- $dbgTime->cur = time();
- if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
- trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
- return;
- }
- $task = self::nextTaskAction();
- if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if (!$task) {
- $dbgTime->cur = time();
- break;
- }
- }
- $customSync = new SyncPermsCustomTables();
- $customSync->run();
- $dbgTime->cur = time();
- $dbgTime->endTime = microtime(true);
- trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- self::sendNotify();
- Lib::loadClass('Router');
- echo "DBG: UrlAction_WmsGenerate->doGenerate() START...\n";
- Router::getRoute('UrlAction_WmsGenerate')->doGenerate();
- echo "DBG: UrlAction_WmsGenerate->doGenerate() END\n";
- echo "DBG: UrlAction_BiAuditGenerate->doGenerate() START...\n";
- Router::getRoute('UrlAction_BiAuditGeneratee')->doGenerate();
- echo "DBG: UrlAction_BiAuditGenerate->doGenerate() END\n";
- }
- public static function sendNotify() {
- Lib::loadClass('Router');
- $cronTaskName = 'sendNotify';
- $keyToken = 'bach_sync_perms';
- $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
- echo "DBG: token = '{$token}'" . "\n";
- $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
- if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
- //file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
- function runUrlTask($url) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_VERBOSE, true);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- $return = curl_exec($ch);
- curl_close($ch);
- return $return;
- }
- $string = runUrlTask("{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task={$cronTaskName}");
- echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
- }
- public static function installTable() {
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "
- CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
- `ID` int(11) NOT NULL AUTO_INCREMENT,
- `ID_PROJECT` int(11) NOT NULL,
- `L_APPOITMENT_USER` varchar(64) DEFAULT '',
- `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
- `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
- `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
- `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
- `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
- `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
- PRIMARY KEY (`ID`),
- UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
- ";
- $db->query($sql);
- $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
- $db->query($sql);
- $sql = "
- CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
- FOR EACH ROW BEGIN
- IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
- update `_SYNC_FILE_PERMS` as s set
- s.`A_SYNCHRONIZED`=0
- where
- s.`ID_PROJECT`=NEW.`ID_PROJECT`
- or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
- END IF;
- END
- ";
- $db->query($sql);
- $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
- $db->query($sql);
- $sql = "
- CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
- FOR EACH ROW BEGIN
- IF NEW.`ID_PROJECT` > 0 THEN
- update `_SYNC_FILE_PERMS` as s set
- s.`A_SYNCHRONIZED`=0
- where
- s.`ID_PROJECT`=NEW.`ID_PROJECT`;
- END IF;
- END
- ";
- $db->query($sql);
- if (V::get('DBG', '', $_GET, 'int') > 0) {
- if ($db->has_errors()) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
- }
- }
- }
- public static function newFilesAction() {
- $task = self::getTaskNewFiles();
- $taskResult = self::fixLastModifiedFiles($task);
- self::saveTask(-1);
- }
- public static function nextTaskAction() {
- $task = self::getTask();
- if (!$task) return false;
- self::executeTask($task);
- /*
- if (isset($task->A_SYNC_RESULT->total)
- && isset($task->A_SYNC_RESULT->lastDone)
- && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
- ) {
- self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
- } else {
- self::saveTask($task->ID_PROJECT);
- }
- */
- self::saveTask($task->ID_PROJECT);
- return $task;
- }
- public static function generateTasksUpdated() {
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
- from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
- where
- s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
- and (
- s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
- or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
- or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
- or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
- )
- ";
- $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
- set
- s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
- , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
- , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
- , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
- , s.`A_SYNCHRONIZED`=0
- where
- s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
- and (
- s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
- or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
- or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
- or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
- )
- ";
- $res = $db->query($sql);
- }
- public static function generateTasksNewRecords() {
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
- values (-1, '', '', '', '');
- ";
- $res = $db->query($sql);
- $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
- select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
- from `IN7_MK_BAZA_DYSTRYBUCJI` as p
- left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
- where p.`A_STATUS`!='DELETED'
- ";
- $res = $db->query($sql);
- }
- /**
- * Znajdź najstarszy aktualizowany projekt.
- */
- public static function getTask() {
- $task = null;
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
- if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
- $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
- }
- $sql = "select s.*
- , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
- , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
- , p.`A_CLASSIFIED` as p__A_CLASSIFIED
- , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
- , p.`M_DIST_DESC` as p__M_DIST_DESC
- , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
- , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
- from `_SYNC_FILE_PERMS` as s
- left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
- left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
- where
- {$sqlWhereProjID}
- order by s.`A_LAST_SYNC` asc, s.`ID` asc
- limit 1
- ";
- $res = $db->query($sql);
- if ($r = $db->fetch($res)) {
- $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
- $task = $r;
- }
- return $task;
- }
- public static function getTaskNewerUsers() {
- $task = null;
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "select s.*
- from `_SYNC_FILE_PERMS` as s
- where s.`ID_PROJECT`=-2
- ";
- $res = $db->query($sql);
- if ($r = $db->fetch($res)) {
- $task = $r;
- }
- if (!$task) {
- $task = new stdClass();
- $task->ID_PROJECT = -2;
- $task->A_SYNC_RESULT = new stdClass();
- $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
- //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
- }
- return $task;
- }
- public static function getTaskNewFiles() {
- $task = null;
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "select s.*
- from `_SYNC_FILE_PERMS` as s
- where s.`ID_PROJECT`=-1
- ";
- $res = $db->query($sql);
- if ($r = $db->fetch($res)) {
- $task = $r;
- }
- if (!$task) {
- $task = new stdClass();
- $task->ID_PROJECT = -1;
- $task->A_SYNC_RESULT = new stdClass();
- $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
- $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
- }
- return $task;
- }
- public static function saveTask($idProject, $taskDone = 1, $result = null) {
- $task = null;
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sqlResult = '';
- if ($result) {
- $resultJson = json_encode($result);
- $resultJson = $db->_($resultJson);
- $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
- }
- $sql = "update `_SYNC_FILE_PERMS` as s
- set
- s.`A_LAST_SYNC`=NOW()
- , s.`A_SYNCHRONIZED`={$taskDone}
- {$sqlResult}
- where s.`ID_PROJECT`={$idProject}
- ";
- $res = $db->query($sql);
- return $task;
- }
- public static function executeTask(&$task) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
- $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
- $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
- $project = new stdClass();
- $project->ID = $task->ID_PROJECT;
- $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
- $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
- $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
- $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
- $project->M_DIST_DESC = $task->p__M_DIST_DESC;
- $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
- $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $project);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- trigger_error("Error: folders config!", E_USER_NOTICE);
- die("Error: folders config!");
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
- if (!$mainFolder) {
- $mainFolder = $uploader->generateFolderName();
- $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
- mkdir($mainFolderPath, 0770, true);
- @chmod($mainFolderPath, 0770);
- if (!file_exists($mainFolderPath)) {
- trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
- return false;
- }
- $requirePermsExt = self::getRequiredPermsExtByRecord($project);
- $file = new stdClass();
- $file->name = '.';
- $file->path = '.';
- //$file->owner = '';
- //$file->group = '';
- //$file->perms = '';
- $file->isDir = true;
- $file->permsExt = array();
- $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- }
- else {
- $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
- $folderPismaPath = "{$mainFolderPath}/_PISMA";
- // if folder _PISMA not exists then create
- $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
- $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
- if (!empty($cmdKorepList)) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
- foreach ($cmdKorepList as $vCmd) {
- $cmdList[] = $vCmd;
- }
- }
- }
- if (!empty($cmdList)) {
- foreach ($cmdList as $vCmd) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
- exec($vCmd, $out, $outValue);
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
- if ($outValue != 0) {
- trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
- }
- public static function getActiveLoginList() {
- static $activeLoginList;
- if (!is_array($activeLoginList)) {
- $activeLoginList = array();
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "select u.`ADM_ACCOUNT`
- from `ADMIN_USERS` as u
- where u.`A_STATUS` = 'NORMAL'
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $activeLoginList[] = $r->ADM_ACCOUNT;
- }
- }
- return $activeLoginList;
- }
- public static function isActiveUser($login) {
- $activeLoginList = self::getActiveLoginList();
- return in_array($login, $activeLoginList);
- }
- public static function getRequiredPermsExtByRecord($project) {
- // TODO: need to check if user is correct in field L_APPOITMENT_USER
- $requirePermsExt = array();
- if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
- // TODO: group PODMIOT
- $requirePermsExt["group:workgroup"] = array('write', 'read');
- }
- else {
- if ($project->L_APPOITMENT_USER) {
- if (self::isActiveUser($project->L_APPOITMENT_USER)) {
- $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
- } else {
- // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
- }
- }
- if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
- $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
- }
- else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
- $requirePermsExt["group:workgroup"] = array('write', 'read');
- }
- else {
- if ($project->A_ADM_COMPANY) {
- $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
- }
- if ($project->A_CLASSIFIED) {
- $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
- }
- }
- }
- // add parent owner
- if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
- if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
- $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
- } else {
- // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
- }
- }
- // add user:_www perms read, write
- $requirePermsExt["user:_www"] = array('write', 'read');
- return $requirePermsExt;
- }
- /**
- * Used for files added/modified by samba/afp.
- *
- * @return TODO: object to store in task->A_SYNC_RESULT
- */
- public static function fixLastModifiedFiles($task) {
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
- $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
- $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
- $foundProjectFiles = array();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
- //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
- exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
- if (!empty($filesWithPerms)) {
- $filesWithPermsTree = array();
- $lastName = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- }
- $file->name = end($fileParts);
- $file->path = end($fileParts);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file->name;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else {// parse error
- $lastName = '..';
- }
- }
- foreach ($filesWithPermsTree as $vFile) {
- $vFile->path = ltrim($vFile->path, './');
- $vFile->path = explode('/', $vFile->path);
- $vFile->projectFolder = array_shift($vFile->path);
- $vFile->path = implode('/', $vFile->path);
- $projId = explode('.', $vFile->projectFolder);
- $projId = reset($projId);
- if (is_numeric($projId) && $projId > 0) {
- $foundProjectFiles[$projId][] = $vFile;
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
- if (!empty($foundProjectFiles)) {
- $sql = "select p.`ID`
- , p.`L_APPOITMENT_USER`
- , p.`A_ADM_COMPANY`
- , p.`A_CLASSIFIED`
- , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
- from IN7_MK_BAZA_DYSTRYBUCJI as p
- left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
- where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $requirePermsExt = self::getRequiredPermsExtByRecord($r);
- foreach ($foundProjectFiles[$r->ID] as $vFile) {
- $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
- if (!empty($cmdList)) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- foreach ($cmdList as $vCmd) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
- exec($vCmd, $out, $outValue);
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
- if ($outValue != 0) {
- trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
- }
- }
- } else {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
- }
- }
- }
- }
- }
- public static function fixProjectKoresp($project, $folderPismaPath) {
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
- $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
- $pismaList = array();
- // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
- $sql = "select k.`ID`
- , k.`K_TYP_KORESP`
- from `IN7_DZIENNIK_KORESP` as k
- where k.`ID_PROJECT`={$project->ID}
- order by k.`ID` DESC
- limit 100
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
- }
- if (empty($pismaList)) {
- return false;
- }
- $lsCmd = array();
- $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
- foreach ($pismaList as $kID => $vTyp) {
- $lsCmd[] = "{$kID}.*/";
- }
- if (empty($lsCmd)) {
- return false;
- }
- $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
- exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
- $filesWithPermsTree = array();
- if (!empty($filesWithPerms)) {
- $lastName = '';
- $folderParent = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- }
- $file->name = end($fileParts);
- $file->path = array();
- if ($folderParent) $file->path[] = $folderParent;
- $file->path[] = end($fileParts);
- $file->path = implode('/', $file->path);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file->name;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else if (substr($line, -1) == ':') {// folder
- $folderParent = trim(substr($line, 0, -1), '/');
- }
- else if (substr($line, 0, 5) == 'total') {
- continue;
- }
- else if (empty($line)) {
- $folderParent = '';
- continue;
- }
- else {// parse error
- $lastName = '..';
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
- $cmdList = array();
- $requirePermsExt = self::getRequiredPermsExtByRecord($project);
- foreach ($filesWithPermsTree as $kFileName => $vFile) {
- $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
- if (!empty($cmdFile)) {
- foreach ($cmdFile as $vCmd) {
- $cmdList[] = $vCmd;
- }
- }
- // if folder _PISMA not exists then create
- $fname = explode('/', $vFile->path);
- $fname = end($fname);
- $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
- }
- return $cmdList;
- }
- /*
- * Not used.
- */
- public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
- if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
- if (isset($task->A_SYNC_RESULT->total)) {
- exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
- if (!empty($filesTotal)) {
- $filesTotal = reset($filesTotal);
- $filesTotal = intval(trim($filesTotal));
- $task->A_SYNC_RESULT->total = $filesTotal;
- self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
- }
- }
- }
- }
- public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
- $time = time();
- if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
- //return false;
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
- $requirePermsExt = self::getRequiredPermsExtByRecord($r);
- $filesWithPerms = array();
- $cmd = " ls -Rlea . ";
- if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
- if (isset($task->A_SYNC_RESULT->total)) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
- if ($task->A_SYNC_RESULT->total > 1000) {
- $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
- if ($lastDone > 0) {
- $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
- $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
- } else {
- $task->A_SYNC_RESULT->lastDone = 1000;
- $cmd = " find . -type f | head -1000 | xargs ls -le ";
- }
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
- exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
- $filesWithPermsTree = array();
- $lastName = '';
- $folderParent = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
- $lastName = '..';
- continue;
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- }
- $file->name = end($fileParts);
- $file->path = array();
- if ($folderParent) $file->path[] = $folderParent;
- $file->path[] = end($fileParts);
- $file->path = implode('/', $file->path);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
- $folderParent = substr($line, 2, -1);
- }
- else if (substr($line, 0, 5) == 'total') {
- continue;
- }
- else if (empty($line)) {
- $folderParent = '';
- continue;
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
- // check perms
- /*
- files:
- W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
- W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
- R read, execute, readattr, readextattr, readsecurity
- dir:
- W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
- W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
- R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
- */
- $cmdList = array();
- foreach ($filesWithPermsTree as $kFileName => $vFile) {
- if (false) {
- // TODO: $kFileName == '_PISMA' - readonly
- // TODO: $vFile->path => _PISMA/...
- }
- else {
- $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
- if (!empty($cmdFile)) {
- foreach ($cmdFile as $vCmd) {
- $cmdList[] = $vCmd;
- }
- }
- }
- }
- return $cmdList;
- }
- public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
- //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
- $cmdList = array();
- $vReqPermsExt = array();
- foreach ($requirePermsExt as $kPermObj => $vPerms) {
- $vReqPermsExt[$kPermObj] = array();
- foreach ($vPerms as $vPerm) {
- if ($vFile->isDir) {
- if ($vPerm == 'read') {
- $vReqPermsExt[$kPermObj]['list'] = 0;
- $vReqPermsExt[$kPermObj]['search'] = 0;
- $vReqPermsExt[$kPermObj]['readattr'] = 0;
- $vReqPermsExt[$kPermObj]['readextattr'] = 0;
- $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
- $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
- $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
- }
- else if ($vPerm == 'write') {
- $vReqPermsExt[$kPermObj]['add_file'] = 0;
- $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
- $vReqPermsExt[$kPermObj]['delete_child'] = 0;
- $vReqPermsExt[$kPermObj]['writeattr'] = 0;
- $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
- $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
- $vReqPermsExt[$kPermObj]['chown'] = 0;
- }
- }
- else {
- if ($vPerm == 'read') {
- $vReqPermsExt[$kPermObj]['read'] = 0;
- $vReqPermsExt[$kPermObj]['execute'] = 0;
- $vReqPermsExt[$kPermObj]['readattr'] = 0;
- $vReqPermsExt[$kPermObj]['readextattr'] = 0;
- $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
- }
- else if ($vPerm == 'write') {
- $vReqPermsExt[$kPermObj]['write'] = 0;
- $vReqPermsExt[$kPermObj]['append'] = 0;
- $vReqPermsExt[$kPermObj]['writeattr'] = 0;
- $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
- $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
- $vReqPermsExt[$kPermObj]['chown'] = 0;
- }
- }
- }
- }
- $permsToRemove = array();
- foreach ($vFile->permsExt as $vPermExtLine) {
- $vPermExtArr = explode(' ', $vPermExtLine);
- $vPermExt = new stdClass();
- $vPermExt->nr = trim($vPermExtArr[0], ' :');
- $vPermExt->permObj = $vPermExtArr[1];
- $vPermExt->perms = '';
- if (count($vPermExtArr) == 4) {
- $vPermExt->perms = explode(',', $vPermExtArr[3]);
- }
- else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
- $vPermExt->perms = explode(',', $vPermExtArr[4]);
- }
- else {
- echo "Error: Perm Ext Line format! ({$vPermExtLine})";
- continue;
- }
- $permFound = false;
- foreach ($vReqPermsExt as $kPermObj => $vPerms) {
- if (false !== strpos($vPermExtLine, $kPermObj)) {
- foreach ($vPerms as $kPerm => $vPermChecked) {
- if (in_array($kPerm, $vPermExt->perms)) {
- $vReqPermsExt[$kPermObj][$kPerm] = 1;
- $permFound = true;
- }
- }
- }
- }
- if (!$permFound) {
- $permsToRemove[] = $vPermExt->nr;
- }
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
- }
- if (!empty($permsToRemove)) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
- $permsToRemove = array_reverse($permsToRemove);
- foreach ($permsToRemove as $vPermInd) {
- $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
- }
- }
- $permsToAdd = array();
- foreach ($vReqPermsExt as $kPermObj => $vPerms) {
- foreach ($vPerms as $kPerm => $vPermChecked) {
- if (!$vPermChecked) {
- $permsToAdd[$kPermObj][$kPerm] = 1;
- }
- }
- }
- if (!empty($permsToAdd)) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
- foreach ($permsToAdd as $kPermObj => $vPerms) {
- $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
- }
- }
- return $cmdList;
- }
- /**
- * @returns array - last modified project ids.
- */
- public static function fixLastModifiedByFiles() {// TODO: RMME
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
- /*
- * $ man find:
- -newer file
- True if the current file has a more recent last modification time than file.
- -newerXY file
- True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
- or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
- ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
- tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
- *
- * $ man chmod:
- -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
- *
- * chmod -a "admin allow write" file1 # remove line
- * chmod -a# 1 file1 # remove line at position 1
- *
- * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
- */
- // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
- $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
- $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
- $foundProjectIds = array();
- $lastRunDate = self::getLastRunDate();
- exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
- if (!empty($foundPaths)) {
- foreach ($foundPaths as $path) {
- $path = ltrim($path, './');
- $folder = explode('/', $path);
- $folder = reset($folder);
- $projId = explode('.', $folder);
- $projId = reset($projId);
- if (is_numeric($projId)) {
- $foundProjectIds[$projId] = $folder;
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
- if (!empty($foundProjectIds)) {
- $sql = "select p.`ID`
- , p.`L_APPOITMENT_USER`
- , p.`A_ADM_COMPANY`
- , p.`A_CLASSIFIED`
- , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
- from IN7_MK_BAZA_DYSTRYBUCJI as p
- left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
- where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $mainFolder = $foundProjectIds[$r->ID];
- $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
- if (!empty($cmdList)) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- } else {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- }
- }
- }
- return array_keys($foundProjectIds);
- }
- public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
- $sqlWhereAdd = '';
- if (!empty($fixedProjIds)) {
- $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
- }
- $projectList = array();
- $lastRunDate = self::getLastRunDate();
- $sql = "select p.`ID`
- , p.`L_APPOITMENT_USER`
- , p.`A_ADM_COMPANY`
- , p.`A_CLASSIFIED`
- , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
- from IN7_MK_BAZA_DYSTRYBUCJI as p
- left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
- where
- ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
- or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
- )
- {$sqlWhereAdd}
- ";
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $projectList[$r->ID] = $r;
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
- }
- public static function getLastRunDate() {// TODO: RMME
- if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
- // Format: 2013-10-07 23:46
- if (strlen($argFromDate) == 16
- && substr($argFromDate, 4, 1) == '-'
- && substr($argFromDate, 7, 1) == '-'
- && substr($argFromDate, 10, 1) == '-'
- && substr($argFromDate, 13, 1) == ':'
- && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
- ) {
- $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
- $lastRunDate = date("Y-m-d H:i", $lastRunDate);
- }
- }
- if (!$lastRunDate) {
- $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
- $lastRunDate = date("Y-m-d H:i", $lastRunDate);
- }
- //$lastRunDate = '2013-09-01 01:00';
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
- return $lastRunDate;
- }
- public static function usersAction() {
- $task = self::getTaskNewerUsers();
- $users = self::getUsersNewerThen($task->A_LAST_SYNC);
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
- self::saveTask(-2);
- }
- public static function usersAllAction() {
- /*
- * DBU - DB User LDU - LDAP User
- * DBG - DB Group LDG - LDAP Group
- *
- * DBU - ADMIN_USERS
- * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
- *
- * 1. fetch DB Users
- * ? only active users (A_STATUS == 'NORMAL')
- * 2. fetch LDAP Users
- *
- * DBU.ADM_ACCOUNT == LDU.uid
- * DBG.A_LDAP_GID == LDG.gidNumber
- *
- * TODO: $group createLdapGroup()
- *
- */
- Lib::loadClass('UsersHelper');
- $users = self::getUsersAll();
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
- $allLdapUsers = UsersHelper::getLDAPUsersAll();
- $ldapUsers = array();
- foreach ($allLdapUsers as $vLdapUser) {
- $ldapUsers[$vLdapUser->uid] = $vLdapUser;
- }
- unset($allLdapUsers);
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
- foreach ($users as $kLogin => $vUser) {
- if ($vUser->A_STATUS == 'NORMAL') {
- if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
- echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
- }
- else {
- echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
- }
- }
- else if ($vUser->A_STATUS == 'DELETED') {
- if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
- echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
- }
- else {
- //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
- }
- }
- }
- }
- public static function getUsersNewerThen($datetime) {
- $users = array();
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sqlWhereAdd = "";
- if ($datetime) {
- $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
- } else {
- // TODO: error datetime not set
- }
- $sql = "select u.ID
- , u.`ADM_ACCOUNT`
- , u.`ADM_NAME`
- , u.`A_STATUS`
- from `ADMIN_USERS` as u
- where
- u.`A_STATUS` in('NORMAL', 'DELETED')
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $users[$r->ADM_ACCOUNT] = $r;
- }
- return $users;
- }
- public static function getUsersAll() {
- $users = array();
- $db = DB::getDB();
- if (!$db) die("DB Error: No DB! L." . __LINE__);
- $sql = "select u.ID
- , u.`ADM_ACCOUNT`
- , u.`ADM_NAME`
- , u.`A_STATUS`
- from `ADMIN_USERS` as u
- where
- u.`A_STATUS` in('NORMAL', 'DELETED')
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $users[$r->ADM_ACCOUNT] = $r;
- }
- return $users;
- }
- }
- class SyncPermsCustomTables {
- public $_tbls;
- private $_db;
- private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
- private $_activeLoginList;
- public function run() {
- if (!$this->fetchConfig()) return;
- $this->installTable();
- $this->generateTasksNewRecords();
- $this->generateTasksUpdated();
- $this->newFilesAction();
- $limit = 100;
- for ($i = 0; $i < $limit; $i++) {
- $loopTasksFired = 0;
- foreach ($this->_tbls as $tblName => $tblConf) {
- $task = $this->nextTaskAction($tblName);
- if (!$task) {
- // TODO: rm $tblName from config to prevent searching for task in next loops
- unset($this->_tbls[$tblName]);
- continue;
- }
- $loopTasksFired++;
- }
- if (!$loopTasksFired) break;
- $i += $loopTasksFired;
- }
- }
- public function fetchConfig() {
- $this->_db = DB::getDB();
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $tbls = array();
- $sql = "select c.`CONF_VAL` as tbl_names
- from `CRM_CONFIG` as c
- where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
- ";
- $res = $this->_db->query($sql);
- while ($r = $this->_db->fetch($res)) {
- if (!empty($r->tbl_names)) {
- $tbls = explode("\n", $r->tbl_names);
- }
- }
- //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
- $configTbls = array();
- Lib::loadClass('FoldersConfig');
- if (!empty($tbls)) {
- $folderConfAll = FoldersConfig::getRawData();
- foreach ($tbls as $tblName) {
- $tblName = trim($tblName);
- if (empty($tblName)) continue;
- $confTblName = "{$tblName}_COLUMN";
- if (FoldersConfig::hasConfig($confTblName)) {
- $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
- }
- }
- }
- //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
- if (!empty($configTbls)) {
- $this->_tbls = $configTbls;
- }
- return $this->_tbls;
- }
- public function installTable() {
- if (!$this->_tbls) return;
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $sql = "
- CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
- `ID` int(11) NOT NULL AUTO_INCREMENT,
- `TBL_NAME` varchar(64),
- `TBL_ID` int(11) NOT NULL,
- `L_APPOITMENT_USER` varchar(64) DEFAULT '',
- `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
- `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
- `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
- `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
- `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
- `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
- `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
- PRIMARY KEY (`ID`),
- UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
- ";
- $this->_db->query($sql);
- if ($this->_db->has_errors()) {
- print_r($this->_db->get_errors());
- }
- }
- public function generateTasksNewRecords() {
- if (!$this->_tbls) return;
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $sqlValues = array();
- foreach ($this->_tbls as $tblName => $tblConf) {
- $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
- }
- $sqlValues = implode(',', $sqlValues);
- $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
- values {$sqlValues};
- ";
- $res = $this->_db->query($sql);
- if ($this->_db->has_errors()) {
- print_r($this->_db->get_errors());
- }
- foreach ($this->_tbls as $tblName => $tblConf) {
- $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
- select '{$tblName}' as TBL_NAME
- , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
- , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
- from `{$tblName}` as t
- where t.`A_STATUS`!='DELETED'
- ";
- $res = $this->_db->query($sql);
- if ($this->_db->has_errors()) {
- print_r($this->_db->get_errors());
- }
- }
- }
- public function generateTasksUpdated() {
- if (!$this->_tbls) return;
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- foreach ($this->_tbls as $tblName => $tblConf) {
- $sql = "update `{$this->_syncTblName}` as s
- , `{$tblName}` as t
- -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
- set
- s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
- , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
- , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
- , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
- , s.`A_SYNCHRONIZED`=0
- where
- s.`TBL_ID`=t.`ID`
- and s.`TBL_NAME`='{$tblName}'
- -- and pt.`ID`=t.`P_ID`
- and (
- s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
- or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
- or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
- -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
- )
- ";
- $res = $this->_db->query($sql);
- if ($this->_db->has_errors()) {
- print_r($this->_db->get_errors());
- }
- }
- }
- public function newFilesAction() {
- if (!$this->_tbls) return;
- foreach ($this->_tbls as $tblName => $tblConf) {
- $task = $this->_getTaskNewFiles($tblName);
- $taskResult = $this->_fixLastModifiedFiles($task);
- $this->_saveTask($tblName, -1);
- }
- }
- private function _getTaskNewFiles($tblName) {
- $task = null;
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $sql = "select s.*
- from `{$this->_syncTblName}` as s
- where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
- ";
- $res = $this->_db->query($sql);
- if ($r = $this->_db->fetch($res)) {
- $task = $r;
- }
- if (!$task) {
- $task = new stdClass();
- $task->TBL_NAME = $tblName;
- $task->TBL_ID = -1;
- $task->A_SYNC_RESULT = new stdClass();
- $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
- $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
- }
- return $task;
- }
- private function _fixLastModifiedFiles($task) {
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $tblName = $task->TBL_NAME;
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
- $confTblName = "{$task->TBL_NAME}_COLUMN";
- $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
- $record = null;
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- trigger_error("Error: folders config!", E_USER_NOTICE);
- die("Error: folders config!");
- }
- $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
- $foundTblFiles = array();
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
- //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
- $filesWithPerms = array();
- $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
- exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
- if (!empty($filesWithPerms)) {
- $filesWithPermsTree = array();
- $lastName = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- }
- $file->name = end($fileParts);
- $file->path = end($fileParts);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file->name;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else {// parse error
- $lastName = '..';
- }
- }
- foreach ($filesWithPermsTree as $vFile) {
- $vFile->path = ltrim($vFile->path, './');
- $vFile->path = explode('/', $vFile->path);
- $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
- $vFile->path = implode('/', $vFile->path);
- // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
- $tblId = 0;
- if ($hasRecordOwnFolder) {
- $tblId = explode('.', $vFile->recordFolder);
- $tblId = reset($tblId);
- }
- else {
- $tblId = explode('.', $vFile->path);
- $tblId = reset($tblId);
- }
- if (is_numeric($tblId) && $tblId > 0) {
- $foundTblFiles[$tblId][] = $vFile;
- }
- }
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
- if (!empty($foundTblFiles)) {
- $rowsIds = array_keys($foundTblFiles);
- $sql = "select t.`ID`
- , t.`L_APPOITMENT_USER`
- , t.`A_ADM_COMPANY`
- , t.`A_CLASSIFIED`
- -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
- from `{$task->TBL_NAME}` as t
- -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
- where t.`ID` in (" . implode(',', $rowsIds) . ")
- ";
- $res = $this->_db->query($sql);
- while ($r = $this->_db->fetch($res)) {
- $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
- foreach ($foundTblFiles[$r->ID] as $vFile) {
- $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
- if (!empty($cmdList)) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- foreach ($cmdList as $vCmd) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
- exec($vCmd, $out, $outValue);
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
- if ($outValue != 0) {
- trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
- }
- }
- } else {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
- }
- }
- }
- }
- }
- private function _getRequiredPermsExtByRecord($record) {
- // TODO: need to check if user is correct in field L_APPOITMENT_USER
- $requirePermsExt = array();
- if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
- // TODO: group PODMIOT
- $requirePermsExt["group:workgroup"] = array('write', 'read');
- }
- else {
- if ($record->L_APPOITMENT_USER) {
- if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
- $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
- } else {
- // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
- }
- }
- if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
- $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
- }
- else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
- $requirePermsExt["group:workgroup"] = array('write', 'read');
- }
- else {
- if ($record->A_ADM_COMPANY) {
- $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
- }
- if ($record->A_CLASSIFIED) {
- $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
- }
- }
- }
- // add parent owner
- if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
- if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
- $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
- } else {
- // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
- }
- }
- // add user:_www perms read, write
- $requirePermsExt["user:_www"] = array('write', 'read');
- return $requirePermsExt;
- }
- private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
- //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
- $cmdList = array();
- $vReqPermsExt = array();
- foreach ($requirePermsExt as $kPermObj => $vPerms) {
- $vReqPermsExt[$kPermObj] = array();
- foreach ($vPerms as $vPerm) {
- if ($vFile->isDir) {
- if ($vPerm == 'read') {
- $vReqPermsExt[$kPermObj]['list'] = 0;
- $vReqPermsExt[$kPermObj]['search'] = 0;
- $vReqPermsExt[$kPermObj]['readattr'] = 0;
- $vReqPermsExt[$kPermObj]['readextattr'] = 0;
- $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
- $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
- $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
- }
- else if ($vPerm == 'write') {
- $vReqPermsExt[$kPermObj]['add_file'] = 0;
- $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
- $vReqPermsExt[$kPermObj]['delete_child'] = 0;
- $vReqPermsExt[$kPermObj]['writeattr'] = 0;
- $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
- $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
- $vReqPermsExt[$kPermObj]['chown'] = 0;
- }
- }
- else {
- if ($vPerm == 'read') {
- $vReqPermsExt[$kPermObj]['read'] = 0;
- $vReqPermsExt[$kPermObj]['execute'] = 0;
- $vReqPermsExt[$kPermObj]['readattr'] = 0;
- $vReqPermsExt[$kPermObj]['readextattr'] = 0;
- $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
- }
- else if ($vPerm == 'write') {
- $vReqPermsExt[$kPermObj]['write'] = 0;
- $vReqPermsExt[$kPermObj]['append'] = 0;
- $vReqPermsExt[$kPermObj]['writeattr'] = 0;
- $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
- $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
- $vReqPermsExt[$kPermObj]['chown'] = 0;
- }
- }
- }
- }
- $permsToRemove = array();
- foreach ($vFile->permsExt as $vPermExtLine) {
- $vPermExtArr = explode(' ', $vPermExtLine);
- $vPermExt = new stdClass();
- $vPermExt->nr = trim($vPermExtArr[0], ' :');
- $vPermExt->permObj = $vPermExtArr[1];
- $vPermExt->perms = '';
- if (count($vPermExtArr) == 4) {
- $vPermExt->perms = explode(',', $vPermExtArr[3]);
- }
- else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
- $vPermExt->perms = explode(',', $vPermExtArr[4]);
- }
- else {
- echo "Error: Perm Ext Line format! ({$vPermExtLine})";
- continue;
- }
- $permFound = false;
- foreach ($vReqPermsExt as $kPermObj => $vPerms) {
- if (false !== strpos($vPermExtLine, $kPermObj)) {
- foreach ($vPerms as $kPerm => $vPermChecked) {
- if (in_array($kPerm, $vPermExt->perms)) {
- $vReqPermsExt[$kPermObj][$kPerm] = 1;
- $permFound = true;
- }
- }
- }
- }
- if (!$permFound) {
- $permsToRemove[] = $vPermExt->nr;
- }
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
- }
- if (!empty($permsToRemove)) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
- $permsToRemove = array_reverse($permsToRemove);
- foreach ($permsToRemove as $vPermInd) {
- $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
- }
- }
- $permsToAdd = array();
- foreach ($vReqPermsExt as $kPermObj => $vPerms) {
- foreach ($vPerms as $kPerm => $vPermChecked) {
- if (!$vPermChecked) {
- $permsToAdd[$kPermObj][$kPerm] = 1;
- }
- }
- }
- if (!empty($permsToAdd)) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
- foreach ($permsToAdd as $kPermObj => $vPerms) {
- $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
- }
- }
- return $cmdList;
- }
- private function _isActiveUser($usrLogin) {
- $activeLoginList = $this->_fetchActiveLoginList();
- return in_array($usrLogin, $activeLoginList);
- }
- public function _fetchActiveLoginList() {
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- if (!is_array($this->_activeLoginList)) {
- $this->_activeLoginList = array();
- $sql = "select u.`ADM_ACCOUNT`
- from `ADMIN_USERS` as u
- where u.`A_STATUS` = 'NORMAL'
- ";
- $res = $this->_db->query($sql);
- while ($r = $this->_db->fetch($res)) {
- $this->_activeLoginList[] = $r->ADM_ACCOUNT;
- }
- }
- return $this->_activeLoginList;
- }
- private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $sqlResult = '';
- if ($result) {
- $resultJson = json_encode($result);
- $resultJson = $this->_db->_($resultJson);
- $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
- }
- $sql = "update `{$this->_syncTblName}` as s
- set
- s.`A_LAST_SYNC`=NOW()
- , s.`A_SYNCHRONIZED`={$taskDone}
- {$sqlResult}
- where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
- ";
- $res = $this->_db->query($sql);
- }
- public function executeTask($tblName, $tblId) {
- if (!$this->_tbls) return;
- $task = $this->_getTask($tblName, $tblId);
- if (!$task) return;
- $this->_executeTask($task);
- $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
- return $task;
- }
- public function nextTaskAction($tblName) {
- if (!$this->_tbls) return;
- $task = $this->_getTask($tblName);
- if (!$task) return;
- $this->_executeTask($task);
- /*
- if (isset($task->A_SYNC_RESULT->total)
- && isset($task->A_SYNC_RESULT->lastDone)
- && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
- ) {
- $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
- } else {
- $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
- }
- */
- $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
- return $task;
- }
- private function _getTask($tblName, $tblId = null) {
- if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
- $task = null;
- $recordFieldList = $this->_getRecordFieldList($tblName);
- $recordFieldList[] = 'L_APPOITMENT_USER';
- $recordFieldList[] = 'A_ADM_COMPANY';
- $recordFieldList[] = 'A_CLASSIFIED';
- $sqlRecordFields = array();
- foreach ($recordFieldList as $fldName) {
- $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
- }
- $sqlRecordFields = implode(',', $sqlRecordFields);
- $sqlTblId = "and s.`TBL_ID`!=-1";
- if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
- $sql = "select s.*
- , {$sqlRecordFields}
- -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
- from `{$this->_syncTblName}` as s
- left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
- -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
- where
- s.`TBL_NAME`='{$tblName}'
- {$sqlTblId}
- and s.`A_SYNCHRONIZED`=0
- and s.`A_POMIN_SYNC`=0
- order by s.`A_LAST_SYNC` asc, s.`ID` asc
- limit 1
- ";
- $res = $this->_db->query($sql);
- if ($r = $this->_db->fetch($res)) {
- $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
- $task = $r;
- $task->record = new stdClass();
- foreach ($recordFieldList as $fldName) {
- $aliasFldName = "t__{$fldName}";
- $task->record->{$fldName} = $task->{$aliasFldName};
- unset($task->{$aliasFldName});
- }
- }
- return $task;
- }
- private function _getRecordFieldList($tblName) {
- if (empty($this->_tbls[$tblName])) return;
- $conf = $this->_tbls[$tblName];
- $fldNames = array();
- $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
- $fldName = trim($fldName);
- if (!empty($fldName)) $fldNames[$fldName] = true;
- for ($i = 1; $i < 5; $i++) {
- $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
- $fldName = trim($fldName);
- if (!empty($fldName)) $fldNames[$fldName] = true;
- $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
- $fldName = trim($fldName);
- if (!empty($fldName)) $fldNames[$fldName] = true;
- }
- if (!in_array('ID', $fldNames)) {
- $fldNames['ID'] = true;
- }
- return array_keys($fldNames);
- }
- private function _executeTask($task) {
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
- $DBG_TIME = false;
- $dbgTime = new stdClass();
- $dbgTime->startTime = microtime(true);
- $dbgTime->lastTime = $dbgTime->startTime;
- $confTblName = "{$task->TBL_NAME}_COLUMN";
- $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
- $record = $task->record;
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- trigger_error("Error: folders config!", E_USER_NOTICE);
- die("Error: folders config!");
- }
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
- if (!$mainFolder) {
- $mainFolder = $uploader->generateFolderName();
- $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
- if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
- @mkdir($mainFolderPath, 0770, true);
- @chmod($mainFolderPath, 0770);
- if (!file_exists($mainFolderPath)) {
- trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
- return false;
- }
- $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
- $file = new stdClass();
- $file->name = '.';
- $file->path = '.';
- //$file->owner = '';
- //$file->group = '';
- //$file->perms = '';
- $file->isDir = true;
- $file->permsExt = array();
- $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
- }
- else {
- $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
- }
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if (!empty($cmdList)) {
- foreach ($cmdList as $vCmd) {
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
- exec($vCmd, $out, $outValue);
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
- if ($outValue != 0) {
- trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
- }
- }
- }
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
- }
- public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
- $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
- $DBG_TIME = false;
- $dbgTime = new stdClass();
- $dbgTime->startTime = microtime(true);
- $dbgTime->lastTime = $dbgTime->startTime;
- $filesWithPerms = array();
- if ($uploader->hasRecordOwnFolder()) {
- $cmd = " ls -Rlea . ";
- $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
- exec($cmd, $filesWithPerms);
- }
- else {
- $lookGlob = $uploader->getFileSearchRegex();
- $cmd = " ls -Rlea {$lookGlob} ";
- $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
- exec($cmd, $filesWithPerms);
- }
- //echo "\n-----------------------\n";
- //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- $filesWithPermsTree = array();
- $lastName = '';
- $folderParent = '';
- foreach ($filesWithPerms as $line) {
- if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
- $fileParts = array();
- $filePartsArr = explode(' ', $line);
- $lastInd = 0;
- foreach ($filePartsArr as $vPart) {
- if ($lastInd > 7) {// file name
- $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
- $lastInd++;
- }
- else if (!empty($vPart) || $vPart === '0') {
- $fileParts[] = $vPart;
- $lastInd++;
- }
- }
- if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
- $lastName = '..';
- continue;
- }
- $file = new stdClass();
- if (!isset($fileParts[8])) {
- echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
- //continue;
- }
- $file->name = end($fileParts);
- $file->path = array();
- if ($folderParent) $file->path[] = $folderParent;
- $file->path[] = end($fileParts);
- $file->path = implode('/', $file->path);
- //$file->owner = $fileParts[2];
- //$file->group = $fileParts[3];
- //$file->perms = $fileParts[0];
- $file->isDir = (substr($line, 0, 1) == 'd');
- $file->permsExt = array();
- $filesWithPermsTree[$file->name] = $file;
- $lastName = $file;
- }
- else if (substr($line, 0, 1) == ' ') {// extended perm line
- if ($lastName == '..') {
- continue;
- }
- $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
- }
- else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
- $folderParent = substr($line, 2, -1);
- }
- else if (substr($line, 0, 5) == 'total') {
- continue;
- }
- else if (empty($line)) {
- $folderParent = '';
- continue;
- }
- }
- //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
- // check perms
- /*
- files:
- W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
- W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
- R read, execute, readattr, readextattr, readsecurity
- dir:
- W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
- W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
- R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
- */
- $cmdList = array();
- foreach ($filesWithPermsTree as $kFileName => $vFile) {
- if (false) {
- // TODO: $kFileName == '_PISMA' - readonly
- // TODO: $vFile->path => _PISMA/...
- }
- else {
- $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
- if (!empty($cmdFile)) {
- foreach ($cmdFile as $vCmd) {
- $cmdList[] = $vCmd;
- }
- }
- }
- }
- //echo "cmdList: ";print_r($cmdList);echo "\n";
- //echo "\n-----------------------\n";
- if ($DBG_TIME) {
- $dbgTime->curTime = microtime(true);
- echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
- $dbgTime->lastTime = $dbgTime->curTime;
- }
- return $cmdList;
- }
- }
- ?>
|