bash_sync_perms.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #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' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  76. Lib::loadClass('V');
  77. Lib::loadClass('Config');
  78. Lib::loadClass('DB');
  79. Lib::loadClass('User');
  80. Lib::loadClass('FoldersConfig');
  81. Lib::loadClass('FileUploader');
  82. if (isset($_SERVER["argv"][1])) {
  83. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  84. }
  85. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  86. $info = array();
  87. $info['max_execution_time'] = ini_get('max_execution_time');
  88. $info['memory_limit'] = ini_get('memory_limit');
  89. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  90. ini_set('max_execution_time', 300);
  91. ini_set('memory_limit', '512M');
  92. $info = array();
  93. $info['max_execution_time'] = ini_get('max_execution_time');
  94. $info['memory_limit'] = ini_get('memory_limit');
  95. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  96. }
  97. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  98. SyncPerms::run(null, null, 'users', null);
  99. }
  100. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  101. SyncPerms::run(null, null, 'usersAll', null);
  102. }
  103. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  104. SyncPerms::run(null, null, 'nextTask', null);
  105. }
  106. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  107. SyncPerms::run(null, null, 'newFiles', null);
  108. }
  109. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  110. $cmd = " ls -Rlea . ";
  111. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  112. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  113. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  114. $filesWithPermsTree = array();
  115. $lastName = '';
  116. $folderParent = '';
  117. foreach ($filesWithPerms as $line) {
  118. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  119. $fileParts = array();
  120. $filePartsArr = explode(' ', $line);
  121. $lastInd = 0;
  122. foreach ($filePartsArr as $vPart) {
  123. if ($lastInd > 7) {// file name
  124. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  125. $lastInd++;
  126. }
  127. else if (!empty($vPart) || $vPart === '0') {
  128. $fileParts[] = $vPart;
  129. $lastInd++;
  130. }
  131. }
  132. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  133. $lastName = '..';
  134. continue;
  135. }
  136. $file = new stdClass();
  137. if (!isset($fileParts[8])) {
  138. 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>';
  139. //continue;
  140. } else {
  141. // fix file name from bad chars
  142. // [8] => CV_Kowalski Mariusz`.pdf
  143. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  144. // [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
  145. // [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
  146. // [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
  147. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  148. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  149. }
  150. 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>';
  151. $file->name = end($fileParts);
  152. $file->path = array();
  153. if ($folderParent) $file->path[] = $folderParent;
  154. $file->path[] = end($fileParts);
  155. $file->path = implode('/', $file->path);
  156. //$file->owner = $fileParts[2];
  157. //$file->group = $fileParts[3];
  158. //$file->perms = $fileParts[0];
  159. $file->isDir = (substr($line, 0, 1) == 'd');
  160. $file->permsExt = array();
  161. $filesWithPermsTree[$file->name] = $file;
  162. $lastName = $file;
  163. }
  164. else if (substr($line, 0, 1) == ' ') {// extended perm line
  165. if ($lastName == '..') {
  166. continue;
  167. }
  168. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  169. }
  170. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  171. $folderParent = substr($line, 2, -1);
  172. }
  173. else if (substr($line, 0, 5) == 'total') {
  174. continue;
  175. }
  176. else if (empty($line)) {
  177. $folderParent = '';
  178. continue;
  179. }
  180. }
  181. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  182. }
  183. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  184. SyncPerms::run(null, null);
  185. }
  186. else {
  187. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  188. }
  189. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  190. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  191. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  192. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  193. }
  194. class SyncPerms {
  195. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  196. if ($arg2 == 'addToLaunchctl') self::task__addToLaunchctl($domain);
  197. else if ($arg2 == 'newFiles') self::task__newFiles();
  198. else if ($arg2 == 'nextTask') self::task__nextTask();
  199. else if ($arg2 == 'testErrorLog') self::task__testErrorLog();
  200. else if ($arg2 == 'users') self::usersAction();
  201. else if ($arg2 == 'usersAll') self::usersAllAction();
  202. else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
  203. else if ($arg2 == 'sendNofity') self::sendNofity();
  204. else self::task__default();
  205. }
  206. public static function task__addToLaunchctl($domain) {
  207. $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
  208. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  209. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  210. <plist version=\"1.0\">
  211. <dict>
  212. <key>Disabled</key>
  213. <false/>
  214. <key>Label</key>
  215. <string>pl.biallnet.sync_perms.{$domain}.php</string>
  216. <key>UserName</key>
  217. <string>root</string>
  218. <key>ProgramArguments</key>
  219. <array>
  220. <string>php</string>
  221. <string>{$_SERVER["argv"][0]}</string>
  222. <string>{$_SERVER["argv"][1]}</string>
  223. </array>
  224. <key>StartInterval</key>
  225. <integer>60</integer>
  226. </dict>
  227. </plist>
  228. \" > {$plistFile}");
  229. echo "Run as root: launchctl load {$plistFile} \n";
  230. }
  231. public static function task__newFiles() {
  232. $time = new stdClass();
  233. $time->start = time();
  234. self::newFilesAction();
  235. $time->end = time();
  236. // TODO: print operation time if DBG
  237. }
  238. public static function task__nextTask() {
  239. $time = new stdClass();
  240. $time->start = time();
  241. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  242. self::installTable();
  243. 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>';}
  244. self::generateTasksNewRecords();
  245. 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>';}
  246. self::generateTasksUpdated();
  247. 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>';}
  248. $limit = V::get('_limit', 1, $_GET, 'int');
  249. for ($i = 0; $i < $limit; $i++) {
  250. $time->cur = time();
  251. if ($time->cur - $time->start > 60 * 5) {
  252. 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>';}
  253. break;
  254. }
  255. $task = self::nextTaskAction();
  256. if (!$task) break;
  257. }
  258. }
  259. public static function task__testErrorLog() {
  260. echo "display_errors: " . ini_get("display_errors") . "\n";
  261. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  262. echo "log_errors: " . ini_get("log_errors") . "\n";
  263. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  264. echo "error_log: " . ini_get("error_log") . "\n";
  265. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  266. }
  267. public static function task__SyncPermsCustomTables() {
  268. $DBG_TIME = true;
  269. $dbgTime = new stdClass();
  270. $dbgTime->startTime = microtime(true);
  271. $dbgTime->lastTime = $dbgTime->startTime;
  272. $customSync = new SyncPermsCustomTables();
  273. // TODO: $customSync->run();
  274. $customSync->fetchConfig();
  275. if ($DBG_TIME) {
  276. $dbgTime->curTime = microtime(true);
  277. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  278. $dbgTime->lastTime = $dbgTime->curTime;
  279. }
  280. $customSync->installTable();
  281. if ($DBG_TIME) {
  282. $dbgTime->curTime = microtime(true);
  283. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  284. $dbgTime->lastTime = $dbgTime->curTime;
  285. }
  286. $rowId = (int)$arg3;
  287. if ($rowId > 0) {
  288. $customSync->executeTask('DEALS_TABLE', $rowId);// TODO: DEALS_TABLE ?
  289. }
  290. else {
  291. $customSync->generateTasksNewRecords();
  292. if ($DBG_TIME) {
  293. $dbgTime->curTime = microtime(true);
  294. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  295. $dbgTime->lastTime = $dbgTime->curTime;
  296. }
  297. $customSync->generateTasksUpdated();
  298. if ($DBG_TIME) {
  299. $dbgTime->curTime = microtime(true);
  300. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  301. $dbgTime->lastTime = $dbgTime->curTime;
  302. }
  303. $customSync->newFilesAction();
  304. if ($DBG_TIME) {
  305. $dbgTime->curTime = microtime(true);
  306. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  307. $dbgTime->lastTime = $dbgTime->curTime;
  308. }
  309. $limit = 1000;
  310. for ($i = 0; $i < $limit; $i++) {
  311. $loopTasksFired = 0;
  312. foreach ($customSync->_tbls as $tblName => $tblConf) {
  313. $task = $customSync->nextTaskAction($tblName);
  314. if ($DBG_TIME) {
  315. $dbgTime->curTime = microtime(true);
  316. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  317. $dbgTime->lastTime = $dbgTime->curTime;
  318. }
  319. if (!$task) {
  320. // TODO: rm $tblName from config to prevent searching for task in next loops
  321. unset($customSync->_tbls[$tblName]);
  322. continue;
  323. }
  324. $loopTasksFired++;
  325. }
  326. if (!$loopTasksFired) {
  327. if ($DBG_TIME) {
  328. $dbgTime->curTime = microtime(true);
  329. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  330. $dbgTime->lastTime = $dbgTime->curTime;
  331. }
  332. break;
  333. }
  334. $i += $loopTasksFired;
  335. }
  336. }
  337. $dbgTime->endTime = microtime(true);
  338. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  339. }
  340. public static function task__default() {
  341. $DBG_TIME = false;
  342. $DBG_MEMORY = false;
  343. $dbgTime = new stdClass();
  344. $dbgTime->start = time();
  345. $dbgTime->startTime = microtime(true);
  346. $dbgTime->lastTime = $dbgTime->startTime;
  347. self::installTable();
  348. if ($DBG_TIME) {
  349. $dbgTime->curTime = microtime(true);
  350. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  351. $dbgTime->lastTime = $dbgTime->curTime;
  352. }
  353. self::generateTasksNewRecords();
  354. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  355. if ($DBG_TIME) {
  356. $dbgTime->curTime = microtime(true);
  357. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  358. $dbgTime->lastTime = $dbgTime->curTime;
  359. }
  360. self::generateTasksUpdated();
  361. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  362. if ($DBG_TIME) {
  363. $dbgTime->curTime = microtime(true);
  364. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  365. $dbgTime->lastTime = $dbgTime->curTime;
  366. }
  367. $dbgTime->cur = time();
  368. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  369. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  370. return;
  371. }
  372. self::newFilesAction();
  373. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  374. if ($DBG_TIME) {
  375. $dbgTime->curTime = microtime(true);
  376. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  377. $dbgTime->lastTime = $dbgTime->curTime;
  378. }
  379. $limit = 100;
  380. for ($i = 0; $i < $limit; $i++) {
  381. $dbgTime->cur = time();
  382. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  383. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  384. return;
  385. }
  386. $task = self::nextTaskAction();
  387. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  388. if ($DBG_TIME) {
  389. $dbgTime->curTime = microtime(true);
  390. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  391. $dbgTime->lastTime = $dbgTime->curTime;
  392. }
  393. if (!$task) {
  394. $dbgTime->cur = time();
  395. break;
  396. }
  397. }
  398. $customSync = new SyncPermsCustomTables();
  399. $customSync->run();
  400. $dbgTime->cur = time();
  401. $dbgTime->endTime = microtime(true);
  402. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  403. if ($DBG_TIME) {
  404. $dbgTime->curTime = microtime(true);
  405. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  406. $dbgTime->lastTime = $dbgTime->curTime;
  407. }
  408. self::sendNofity();
  409. Lib::loadClass('Router');
  410. Router::getRoute('UrlAction_WmsGenerate')->doGenerate();
  411. }
  412. public static function sendNofity() {
  413. Lib::loadClass('Router');
  414. $cronTaskName = 'sendNofity';
  415. $keyToken = 'bach_sync_perms';
  416. $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  417. echo "DBG: token = '{$token}'" . "\n";
  418. $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
  419. if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
  420. //file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNofity");
  421. function runUrlTask($url) {
  422. $ch = curl_init();
  423. curl_setopt($ch, CURLOPT_VERBOSE, true);
  424. curl_setopt($ch, CURLOPT_URL, $url);
  425. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  426. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  427. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  428. $return = curl_exec($ch);
  429. curl_close($ch);
  430. return $return;
  431. }
  432. $string = runUrlTask("{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task={$cronTaskName}");
  433. echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
  434. }
  435. public static function installTable() {
  436. $db = DB::getDB();
  437. if (!$db) die("DB Error: No DB! L." . __LINE__);
  438. $sql = "
  439. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  440. `ID` int(11) NOT NULL AUTO_INCREMENT,
  441. `ID_PROJECT` int(11) NOT NULL,
  442. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  443. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  444. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  445. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  446. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  447. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  448. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  449. PRIMARY KEY (`ID`),
  450. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  451. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  452. ";
  453. $db->query($sql);
  454. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  455. $db->query($sql);
  456. $sql = "
  457. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  458. FOR EACH ROW BEGIN
  459. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  460. update `_SYNC_FILE_PERMS` as s set
  461. s.`A_SYNCHRONIZED`=0
  462. where
  463. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  464. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  465. END IF;
  466. END
  467. ";
  468. $db->query($sql);
  469. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  470. $db->query($sql);
  471. $sql = "
  472. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  473. FOR EACH ROW BEGIN
  474. IF NEW.`ID_PROJECT` > 0 THEN
  475. update `_SYNC_FILE_PERMS` as s set
  476. s.`A_SYNCHRONIZED`=0
  477. where
  478. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  479. END IF;
  480. END
  481. ";
  482. $db->query($sql);
  483. if (V::get('DBG', '', $_GET, 'int') > 0) {
  484. if ($db->has_errors()) {
  485. 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>';
  486. }
  487. }
  488. }
  489. public static function newFilesAction() {
  490. $task = self::getTaskNewFiles();
  491. $taskResult = self::fixLastModifiedFiles($task);
  492. self::saveTask(-1);
  493. }
  494. public static function nextTaskAction() {
  495. $task = self::getTask();
  496. if (!$task) return false;
  497. self::executeTask($task);
  498. /*
  499. if (isset($task->A_SYNC_RESULT->total)
  500. && isset($task->A_SYNC_RESULT->lastDone)
  501. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  502. ) {
  503. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  504. } else {
  505. self::saveTask($task->ID_PROJECT);
  506. }
  507. */
  508. self::saveTask($task->ID_PROJECT);
  509. return $task;
  510. }
  511. public static function generateTasksUpdated() {
  512. $db = DB::getDB();
  513. if (!$db) die("DB Error: No DB! L." . __LINE__);
  514. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  515. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  516. where
  517. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  518. and (
  519. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  520. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  521. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  522. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  523. )
  524. ";
  525. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  526. set
  527. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  528. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  529. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  530. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  531. , s.`A_SYNCHRONIZED`=0
  532. where
  533. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  534. and (
  535. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  536. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  537. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  538. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  539. )
  540. ";
  541. $res = $db->query($sql);
  542. }
  543. public static function generateTasksNewRecords() {
  544. $db = DB::getDB();
  545. if (!$db) die("DB Error: No DB! L." . __LINE__);
  546. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  547. values (-1, '', '', '', '');
  548. ";
  549. $res = $db->query($sql);
  550. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  551. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  552. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  553. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  554. where p.`A_STATUS`!='DELETED'
  555. ";
  556. $res = $db->query($sql);
  557. }
  558. /**
  559. * Znajdź najstarszy aktualizowany projekt.
  560. */
  561. public static function getTask() {
  562. $task = null;
  563. $db = DB::getDB();
  564. if (!$db) die("DB Error: No DB! L." . __LINE__);
  565. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  566. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  567. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  568. }
  569. $sql = "select s.*
  570. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  571. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  572. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  573. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  574. , p.`M_DIST_DESC` as p__M_DIST_DESC
  575. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  576. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  577. from `_SYNC_FILE_PERMS` as s
  578. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  579. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  580. where
  581. {$sqlWhereProjID}
  582. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  583. limit 1
  584. ";
  585. $res = $db->query($sql);
  586. if ($r = $db->fetch($res)) {
  587. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  588. $task = $r;
  589. }
  590. return $task;
  591. }
  592. public static function getTaskNewerUsers() {
  593. $task = null;
  594. $db = DB::getDB();
  595. if (!$db) die("DB Error: No DB! L." . __LINE__);
  596. $sql = "select s.*
  597. from `_SYNC_FILE_PERMS` as s
  598. where s.`ID_PROJECT`=-2
  599. ";
  600. $res = $db->query($sql);
  601. if ($r = $db->fetch($res)) {
  602. $task = $r;
  603. }
  604. if (!$task) {
  605. $task = new stdClass();
  606. $task->ID_PROJECT = -2;
  607. $task->A_SYNC_RESULT = new stdClass();
  608. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  609. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  610. }
  611. return $task;
  612. }
  613. public static function getTaskNewFiles() {
  614. $task = null;
  615. $db = DB::getDB();
  616. if (!$db) die("DB Error: No DB! L." . __LINE__);
  617. $sql = "select s.*
  618. from `_SYNC_FILE_PERMS` as s
  619. where s.`ID_PROJECT`=-1
  620. ";
  621. $res = $db->query($sql);
  622. if ($r = $db->fetch($res)) {
  623. $task = $r;
  624. }
  625. if (!$task) {
  626. $task = new stdClass();
  627. $task->ID_PROJECT = -1;
  628. $task->A_SYNC_RESULT = new stdClass();
  629. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  630. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  631. }
  632. return $task;
  633. }
  634. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  635. $task = null;
  636. $db = DB::getDB();
  637. if (!$db) die("DB Error: No DB! L." . __LINE__);
  638. $sqlResult = '';
  639. if ($result) {
  640. $resultJson = json_encode($result);
  641. $resultJson = $db->_($resultJson);
  642. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  643. }
  644. $sql = "update `_SYNC_FILE_PERMS` as s
  645. set
  646. s.`A_LAST_SYNC`=NOW()
  647. , s.`A_SYNCHRONIZED`={$taskDone}
  648. {$sqlResult}
  649. where s.`ID_PROJECT`={$idProject}
  650. ";
  651. $res = $db->query($sql);
  652. return $task;
  653. }
  654. public static function executeTask(&$task) {
  655. 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>';}
  656. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  657. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  658. $project = new stdClass();
  659. $project->ID = $task->ID_PROJECT;
  660. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  661. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  662. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  663. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  664. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  665. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  666. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  667. $folderConf = FoldersConfig::getAll($confTblName);
  668. $uploader = new FileUploader($confTblName, $project);
  669. $errMsg = '';
  670. if (!$uploader->setConfig($folderConf, $errMsg)) {
  671. trigger_error("Error: folders config!", E_USER_NOTICE);
  672. die("Error: folders config!");
  673. }
  674. $uploader->findFolder();
  675. $mainFolder = $uploader->getDestFolder();
  676. 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>';}
  677. if (!$mainFolder) {
  678. $mainFolder = $uploader->generateFolderName();
  679. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  680. 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>';}
  681. mkdir($mainFolderPath, 0770, true);
  682. @chmod($mainFolderPath, 0770);
  683. if (!file_exists($mainFolderPath)) {
  684. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  685. return false;
  686. }
  687. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  688. $file = new stdClass();
  689. $file->name = '.';
  690. $file->path = '.';
  691. //$file->owner = '';
  692. //$file->group = '';
  693. //$file->perms = '';
  694. $file->isDir = true;
  695. $file->permsExt = array();
  696. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  697. 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>';}
  698. }
  699. else {
  700. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  701. 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>';}
  702. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  703. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  704. // if folder _PISMA not exists then create
  705. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  706. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  707. if (!empty($cmdKorepList)) {
  708. 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>';}
  709. foreach ($cmdKorepList as $vCmd) {
  710. $cmdList[] = $vCmd;
  711. }
  712. }
  713. }
  714. if (!empty($cmdList)) {
  715. foreach ($cmdList as $vCmd) {
  716. 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>';}
  717. exec($vCmd, $out, $outValue);
  718. 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>';}
  719. if ($outValue != 0) {
  720. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  721. }
  722. }
  723. }
  724. 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>';}
  725. }
  726. public static function getActiveLoginList() {
  727. static $activeLoginList;
  728. if (!is_array($activeLoginList)) {
  729. $activeLoginList = array();
  730. $db = DB::getDB();
  731. if (!$db) die("DB Error: No DB! L." . __LINE__);
  732. $sql = "select u.`ADM_ACCOUNT`
  733. from `ADMIN_USERS` as u
  734. where u.`A_STATUS` = 'NORMAL'
  735. ";
  736. $res = $db->query($sql);
  737. while ($r = $db->fetch($res)) {
  738. $activeLoginList[] = $r->ADM_ACCOUNT;
  739. }
  740. }
  741. return $activeLoginList;
  742. }
  743. public static function isActiveUser($login) {
  744. $activeLoginList = self::getActiveLoginList();
  745. return in_array($login, $activeLoginList);
  746. }
  747. public static function getRequiredPermsExtByRecord($project) {
  748. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  749. $requirePermsExt = array();
  750. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  751. // TODO: group PODMIOT
  752. $requirePermsExt["group:workgroup"] = array('write', 'read');
  753. }
  754. else {
  755. if ($project->L_APPOITMENT_USER) {
  756. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  757. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  758. } else {
  759. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  760. }
  761. }
  762. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  763. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  764. }
  765. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  766. $requirePermsExt["group:workgroup"] = array('write', 'read');
  767. }
  768. else {
  769. if ($project->A_ADM_COMPANY) {
  770. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  771. }
  772. if ($project->A_CLASSIFIED) {
  773. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  774. }
  775. }
  776. }
  777. // add parent owner
  778. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  779. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  780. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  781. } else {
  782. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  783. }
  784. }
  785. // add user:_www perms read, write
  786. $requirePermsExt["user:_www"] = array('write', 'read');
  787. return $requirePermsExt;
  788. }
  789. /**
  790. * Used for files added/modified by samba/afp.
  791. *
  792. * @return TODO: object to store in task->A_SYNC_RESULT
  793. */
  794. public static function fixLastModifiedFiles($task) {
  795. $db = DB::getDB();
  796. if (!$db) die("DB Error: No DB! L." . __LINE__);
  797. 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>';}
  798. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  799. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  800. $foundProjectFiles = array();
  801. 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>';}
  802. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  803. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  804. if (!empty($filesWithPerms)) {
  805. $filesWithPermsTree = array();
  806. $lastName = '';
  807. foreach ($filesWithPerms as $line) {
  808. if (substr($line, 0, 1) == '-') {// file name
  809. $fileParts = array();
  810. $filePartsArr = explode(' ', $line);
  811. $lastInd = 0;
  812. foreach ($filePartsArr as $vPart) {
  813. if ($lastInd > 7) {// file name
  814. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  815. $lastInd++;
  816. }
  817. else if (!empty($vPart) || $vPart === '0') {
  818. $fileParts[] = $vPart;
  819. $lastInd++;
  820. }
  821. }
  822. $file = new stdClass();
  823. if (!isset($fileParts[8])) {
  824. 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>';
  825. //continue;
  826. }
  827. $file->name = end($fileParts);
  828. $file->path = end($fileParts);
  829. //$file->owner = $fileParts[2];
  830. //$file->group = $fileParts[3];
  831. //$file->perms = $fileParts[0];
  832. $file->isDir = (substr($line, 0, 1) == 'd');
  833. $file->permsExt = array();
  834. $filesWithPermsTree[$file->name] = $file;
  835. $lastName = $file->name;
  836. }
  837. else if (substr($line, 0, 1) == ' ') {// extended perm line
  838. if ($lastName == '..') {
  839. continue;
  840. }
  841. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  842. }
  843. else {// parse error
  844. $lastName = '..';
  845. }
  846. }
  847. foreach ($filesWithPermsTree as $vFile) {
  848. $vFile->path = ltrim($vFile->path, './');
  849. $vFile->path = explode('/', $vFile->path);
  850. $vFile->projectFolder = array_shift($vFile->path);
  851. $vFile->path = implode('/', $vFile->path);
  852. $projId = explode('.', $vFile->projectFolder);
  853. $projId = reset($projId);
  854. if (is_numeric($projId) && $projId > 0) {
  855. $foundProjectFiles[$projId][] = $vFile;
  856. }
  857. }
  858. }
  859. 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>';}
  860. 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>';}
  861. if (!empty($foundProjectFiles)) {
  862. $sql = "select p.`ID`
  863. , p.`L_APPOITMENT_USER`
  864. , p.`A_ADM_COMPANY`
  865. , p.`A_CLASSIFIED`
  866. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  867. from IN7_MK_BAZA_DYSTRYBUCJI as p
  868. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  869. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  870. ";
  871. $res = $db->query($sql);
  872. while ($r = $db->fetch($res)) {
  873. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  874. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  875. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  876. if (!empty($cmdList)) {
  877. 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>';}
  878. foreach ($cmdList as $vCmd) {
  879. 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>';}
  880. exec($vCmd, $out, $outValue);
  881. 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>';}
  882. if ($outValue != 0) {
  883. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  884. }
  885. }
  886. } else {
  887. 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>';}
  888. }
  889. }
  890. }
  891. }
  892. }
  893. public static function fixProjectKoresp($project, $folderPismaPath) {
  894. $db = DB::getDB();
  895. if (!$db) die("DB Error: No DB! L." . __LINE__);
  896. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  897. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  898. $pismaList = array();
  899. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  900. $sql = "select k.`ID`
  901. , k.`K_TYP_KORESP`
  902. from `IN7_DZIENNIK_KORESP` as k
  903. where k.`ID_PROJECT`={$project->ID}
  904. order by k.`ID` DESC
  905. limit 100
  906. ";
  907. $res = $db->query($sql);
  908. while ($r = $db->fetch($res)) {
  909. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  910. }
  911. if (empty($pismaList)) {
  912. return false;
  913. }
  914. $lsCmd = array();
  915. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  916. foreach ($pismaList as $kID => $vTyp) {
  917. $lsCmd[] = "{$kID}.*/";
  918. }
  919. if (empty($lsCmd)) {
  920. return false;
  921. }
  922. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  923. 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>';}
  924. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  925. $filesWithPermsTree = array();
  926. if (!empty($filesWithPerms)) {
  927. $lastName = '';
  928. $folderParent = '';
  929. foreach ($filesWithPerms as $line) {
  930. if (substr($line, 0, 1) == '-') {// file name
  931. $fileParts = array();
  932. $filePartsArr = explode(' ', $line);
  933. $lastInd = 0;
  934. foreach ($filePartsArr as $vPart) {
  935. if ($lastInd > 7) {// file name
  936. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  937. $lastInd++;
  938. }
  939. else if (!empty($vPart) || $vPart === '0') {
  940. $fileParts[] = $vPart;
  941. $lastInd++;
  942. }
  943. }
  944. $file = new stdClass();
  945. if (!isset($fileParts[8])) {
  946. 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>';
  947. //continue;
  948. }
  949. $file->name = end($fileParts);
  950. $file->path = array();
  951. if ($folderParent) $file->path[] = $folderParent;
  952. $file->path[] = end($fileParts);
  953. $file->path = implode('/', $file->path);
  954. //$file->owner = $fileParts[2];
  955. //$file->group = $fileParts[3];
  956. //$file->perms = $fileParts[0];
  957. $file->isDir = (substr($line, 0, 1) == 'd');
  958. $file->permsExt = array();
  959. $filesWithPermsTree[$file->name] = $file;
  960. $lastName = $file->name;
  961. }
  962. else if (substr($line, 0, 1) == ' ') {// extended perm line
  963. if ($lastName == '..') {
  964. continue;
  965. }
  966. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  967. }
  968. else if (substr($line, -1) == ':') {// folder
  969. $folderParent = trim(substr($line, 0, -1), '/');
  970. }
  971. else if (substr($line, 0, 5) == 'total') {
  972. continue;
  973. }
  974. else if (empty($line)) {
  975. $folderParent = '';
  976. continue;
  977. }
  978. else {// parse error
  979. $lastName = '..';
  980. }
  981. }
  982. }
  983. 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>';}
  984. 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>';}
  985. $cmdList = array();
  986. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  987. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  988. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  989. if (!empty($cmdFile)) {
  990. foreach ($cmdFile as $vCmd) {
  991. $cmdList[] = $vCmd;
  992. }
  993. }
  994. // if folder _PISMA not exists then create
  995. $fname = explode('/', $vFile->path);
  996. $fname = end($fname);
  997. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  998. }
  999. return $cmdList;
  1000. }
  1001. /*
  1002. * Not used.
  1003. */
  1004. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  1005. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1006. if (isset($task->A_SYNC_RESULT->total)) {
  1007. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  1008. if (!empty($filesTotal)) {
  1009. $filesTotal = reset($filesTotal);
  1010. $filesTotal = intval(trim($filesTotal));
  1011. $task->A_SYNC_RESULT->total = $filesTotal;
  1012. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  1018. $time = time();
  1019. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1020. 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>';}
  1021. //return false;
  1022. }
  1023. 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>';}
  1024. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1025. $filesWithPerms = array();
  1026. $cmd = " ls -Rlea . ";
  1027. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1028. if (isset($task->A_SYNC_RESULT->total)) {
  1029. 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>';}
  1030. if ($task->A_SYNC_RESULT->total > 1000) {
  1031. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1032. if ($lastDone > 0) {
  1033. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1034. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1035. } else {
  1036. $task->A_SYNC_RESULT->lastDone = 1000;
  1037. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1038. }
  1039. }
  1040. }
  1041. }
  1042. 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>';}
  1043. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1044. 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>';}
  1045. $filesWithPermsTree = array();
  1046. $lastName = '';
  1047. $folderParent = '';
  1048. foreach ($filesWithPerms as $line) {
  1049. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1050. $fileParts = array();
  1051. $filePartsArr = explode(' ', $line);
  1052. $lastInd = 0;
  1053. foreach ($filePartsArr as $vPart) {
  1054. if ($lastInd > 7) {// file name
  1055. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1056. $lastInd++;
  1057. }
  1058. else if (!empty($vPart) || $vPart === '0') {
  1059. $fileParts[] = $vPart;
  1060. $lastInd++;
  1061. }
  1062. }
  1063. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1064. $lastName = '..';
  1065. continue;
  1066. }
  1067. $file = new stdClass();
  1068. if (!isset($fileParts[8])) {
  1069. 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>';
  1070. //continue;
  1071. }
  1072. $file->name = end($fileParts);
  1073. $file->path = array();
  1074. if ($folderParent) $file->path[] = $folderParent;
  1075. $file->path[] = end($fileParts);
  1076. $file->path = implode('/', $file->path);
  1077. //$file->owner = $fileParts[2];
  1078. //$file->group = $fileParts[3];
  1079. //$file->perms = $fileParts[0];
  1080. $file->isDir = (substr($line, 0, 1) == 'd');
  1081. $file->permsExt = array();
  1082. $filesWithPermsTree[$file->name] = $file;
  1083. $lastName = $file;
  1084. }
  1085. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1086. if ($lastName == '..') {
  1087. continue;
  1088. }
  1089. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1090. }
  1091. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1092. $folderParent = substr($line, 2, -1);
  1093. }
  1094. else if (substr($line, 0, 5) == 'total') {
  1095. continue;
  1096. }
  1097. else if (empty($line)) {
  1098. $folderParent = '';
  1099. continue;
  1100. }
  1101. }
  1102. 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>';}
  1103. // check perms
  1104. /*
  1105. files:
  1106. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1107. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1108. R read, execute, readattr, readextattr, readsecurity
  1109. dir:
  1110. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1111. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1112. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1113. */
  1114. $cmdList = array();
  1115. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1116. if (false) {
  1117. // TODO: $kFileName == '_PISMA' - readonly
  1118. // TODO: $vFile->path => _PISMA/...
  1119. }
  1120. else {
  1121. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1122. if (!empty($cmdFile)) {
  1123. foreach ($cmdFile as $vCmd) {
  1124. $cmdList[] = $vCmd;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. return $cmdList;
  1130. }
  1131. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1132. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1133. $cmdList = array();
  1134. $vReqPermsExt = array();
  1135. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1136. $vReqPermsExt[$kPermObj] = array();
  1137. foreach ($vPerms as $vPerm) {
  1138. if ($vFile->isDir) {
  1139. if ($vPerm == 'read') {
  1140. $vReqPermsExt[$kPermObj]['list'] = 0;
  1141. $vReqPermsExt[$kPermObj]['search'] = 0;
  1142. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1143. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1144. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1145. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1146. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1147. }
  1148. else if ($vPerm == 'write') {
  1149. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1150. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1151. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1152. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1153. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1154. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1155. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1156. }
  1157. }
  1158. else {
  1159. if ($vPerm == 'read') {
  1160. $vReqPermsExt[$kPermObj]['read'] = 0;
  1161. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1162. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1163. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1164. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1165. }
  1166. else if ($vPerm == 'write') {
  1167. $vReqPermsExt[$kPermObj]['write'] = 0;
  1168. $vReqPermsExt[$kPermObj]['append'] = 0;
  1169. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1170. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1171. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1172. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. $permsToRemove = array();
  1178. foreach ($vFile->permsExt as $vPermExtLine) {
  1179. $vPermExtArr = explode(' ', $vPermExtLine);
  1180. $vPermExt = new stdClass();
  1181. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1182. $vPermExt->permObj = $vPermExtArr[1];
  1183. $vPermExt->perms = '';
  1184. if (count($vPermExtArr) == 4) {
  1185. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1186. }
  1187. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1188. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1189. }
  1190. else {
  1191. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1192. continue;
  1193. }
  1194. $permFound = false;
  1195. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1196. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1197. foreach ($vPerms as $kPerm => $vPermChecked) {
  1198. if (in_array($kPerm, $vPermExt->perms)) {
  1199. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1200. $permFound = true;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. if (!$permFound) {
  1206. $permsToRemove[] = $vPermExt->nr;
  1207. }
  1208. //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>';
  1209. }
  1210. if (!empty($permsToRemove)) {
  1211. 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>';}
  1212. $permsToRemove = array_reverse($permsToRemove);
  1213. foreach ($permsToRemove as $vPermInd) {
  1214. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1215. }
  1216. }
  1217. $permsToAdd = array();
  1218. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1219. foreach ($vPerms as $kPerm => $vPermChecked) {
  1220. if (!$vPermChecked) {
  1221. $permsToAdd[$kPermObj][$kPerm] = 1;
  1222. }
  1223. }
  1224. }
  1225. if (!empty($permsToAdd)) {
  1226. 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>';}
  1227. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1228. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1229. }
  1230. }
  1231. return $cmdList;
  1232. }
  1233. /**
  1234. * @returns array - last modified project ids.
  1235. */
  1236. public static function fixLastModifiedByFiles() {// TODO: RMME
  1237. $db = DB::getDB();
  1238. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1239. 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>';}
  1240. /*
  1241. * $ man find:
  1242. -newer file
  1243. True if the current file has a more recent last modification time than file.
  1244. -newerXY file
  1245. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1246. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1247. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1248. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1249. *
  1250. * $ man chmod:
  1251. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1252. *
  1253. * chmod -a "admin allow write" file1 # remove line
  1254. * chmod -a# 1 file1 # remove line at position 1
  1255. *
  1256. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1257. */
  1258. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1259. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1260. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1261. $foundProjectIds = array();
  1262. $lastRunDate = self::getLastRunDate();
  1263. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1264. if (!empty($foundPaths)) {
  1265. foreach ($foundPaths as $path) {
  1266. $path = ltrim($path, './');
  1267. $folder = explode('/', $path);
  1268. $folder = reset($folder);
  1269. $projId = explode('.', $folder);
  1270. $projId = reset($projId);
  1271. if (is_numeric($projId)) {
  1272. $foundProjectIds[$projId] = $folder;
  1273. }
  1274. }
  1275. }
  1276. 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>';}
  1277. 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>';}
  1278. if (!empty($foundProjectIds)) {
  1279. $sql = "select p.`ID`
  1280. , p.`L_APPOITMENT_USER`
  1281. , p.`A_ADM_COMPANY`
  1282. , p.`A_CLASSIFIED`
  1283. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1284. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1285. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1286. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1287. ";
  1288. $res = $db->query($sql);
  1289. while ($r = $db->fetch($res)) {
  1290. $mainFolder = $foundProjectIds[$r->ID];
  1291. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1292. if (!empty($cmdList)) {
  1293. 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>';}
  1294. } else {
  1295. 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>';}
  1296. }
  1297. }
  1298. }
  1299. return array_keys($foundProjectIds);
  1300. }
  1301. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1302. $db = DB::getDB();
  1303. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1304. 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>';}
  1305. $sqlWhereAdd = '';
  1306. if (!empty($fixedProjIds)) {
  1307. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1308. }
  1309. $projectList = array();
  1310. $lastRunDate = self::getLastRunDate();
  1311. $sql = "select p.`ID`
  1312. , p.`L_APPOITMENT_USER`
  1313. , p.`A_ADM_COMPANY`
  1314. , p.`A_CLASSIFIED`
  1315. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1316. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1317. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1318. where
  1319. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1320. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1321. )
  1322. {$sqlWhereAdd}
  1323. ";
  1324. 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>';}
  1325. $res = $db->query($sql);
  1326. while ($r = $db->fetch($res)) {
  1327. $projectList[$r->ID] = $r;
  1328. }
  1329. 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>';}
  1330. }
  1331. public static function getLastRunDate() {// TODO: RMME
  1332. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1333. // Format: 2013-10-07 23:46
  1334. if (strlen($argFromDate) == 16
  1335. && substr($argFromDate, 4, 1) == '-'
  1336. && substr($argFromDate, 7, 1) == '-'
  1337. && substr($argFromDate, 10, 1) == '-'
  1338. && substr($argFromDate, 13, 1) == ':'
  1339. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1340. ) {
  1341. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1342. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1343. }
  1344. }
  1345. if (!$lastRunDate) {
  1346. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1347. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1348. }
  1349. //$lastRunDate = '2013-09-01 01:00';
  1350. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1351. return $lastRunDate;
  1352. }
  1353. public static function usersAction() {
  1354. $task = self::getTaskNewerUsers();
  1355. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1356. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1357. self::saveTask(-2);
  1358. }
  1359. public static function usersAllAction() {
  1360. /*
  1361. * DBU - DB User LDU - LDAP User
  1362. * DBG - DB Group LDG - LDAP Group
  1363. *
  1364. * DBU - ADMIN_USERS
  1365. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1366. *
  1367. * 1. fetch DB Users
  1368. * ? only active users (A_STATUS == 'NORMAL')
  1369. * 2. fetch LDAP Users
  1370. *
  1371. * DBU.ADM_ACCOUNT == LDU.uid
  1372. * DBG.A_LDAP_GID == LDG.gidNumber
  1373. *
  1374. * TODO: $group createLdapGroup()
  1375. *
  1376. */
  1377. Lib::loadClass('UsersHelper');
  1378. $users = self::getUsersAll();
  1379. 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>';
  1380. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1381. $ldapUsers = array();
  1382. foreach ($allLdapUsers as $vLdapUser) {
  1383. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1384. }
  1385. unset($allLdapUsers);
  1386. 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>';
  1387. foreach ($users as $kLogin => $vUser) {
  1388. if ($vUser->A_STATUS == 'NORMAL') {
  1389. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1390. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1391. }
  1392. else {
  1393. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1394. }
  1395. }
  1396. else if ($vUser->A_STATUS == 'DELETED') {
  1397. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1398. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1399. }
  1400. else {
  1401. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1402. }
  1403. }
  1404. }
  1405. }
  1406. public static function getUsersNewerThen($datetime) {
  1407. $users = array();
  1408. $db = DB::getDB();
  1409. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1410. $sqlWhereAdd = "";
  1411. if ($datetime) {
  1412. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1413. } else {
  1414. // TODO: error datetime not set
  1415. }
  1416. $sql = "select u.ID
  1417. , u.`ADM_ACCOUNT`
  1418. , u.`ADM_NAME`
  1419. , u.`A_STATUS`
  1420. from `ADMIN_USERS` as u
  1421. where
  1422. u.`A_STATUS` in('NORMAL', 'DELETED')
  1423. ";
  1424. $res = $db->query($sql);
  1425. while ($r = $db->fetch($res)) {
  1426. $users[$r->ADM_ACCOUNT] = $r;
  1427. }
  1428. return $users;
  1429. }
  1430. public static function getUsersAll() {
  1431. $users = array();
  1432. $db = DB::getDB();
  1433. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1434. $sql = "select u.ID
  1435. , u.`ADM_ACCOUNT`
  1436. , u.`ADM_NAME`
  1437. , u.`A_STATUS`
  1438. from `ADMIN_USERS` as u
  1439. where
  1440. u.`A_STATUS` in('NORMAL', 'DELETED')
  1441. ";
  1442. $res = $db->query($sql);
  1443. while ($r = $db->fetch($res)) {
  1444. $users[$r->ADM_ACCOUNT] = $r;
  1445. }
  1446. return $users;
  1447. }
  1448. }
  1449. class SyncPermsCustomTables {
  1450. public $_tbls;
  1451. private $_db;
  1452. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1453. private $_activeLoginList;
  1454. public function run() {
  1455. if (!$this->fetchConfig()) return;
  1456. $this->installTable();
  1457. $this->generateTasksNewRecords();
  1458. $this->generateTasksUpdated();
  1459. $this->newFilesAction();
  1460. $limit = 100;
  1461. for ($i = 0; $i < $limit; $i++) {
  1462. $loopTasksFired = 0;
  1463. foreach ($this->_tbls as $tblName => $tblConf) {
  1464. $task = $this->nextTaskAction($tblName);
  1465. if (!$task) {
  1466. // TODO: rm $tblName from config to prevent searching for task in next loops
  1467. unset($this->_tbls[$tblName]);
  1468. continue;
  1469. }
  1470. $loopTasksFired++;
  1471. }
  1472. if (!$loopTasksFired) break;
  1473. $i += $loopTasksFired;
  1474. }
  1475. }
  1476. public function fetchConfig() {
  1477. $this->_db = DB::getDB();
  1478. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1479. $tbls = array();
  1480. $sql = "select c.`CONF_VAL` as tbl_names
  1481. from `CRM_CONFIG` as c
  1482. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1483. ";
  1484. $res = $this->_db->query($sql);
  1485. while ($r = $this->_db->fetch($res)) {
  1486. if (!empty($r->tbl_names)) {
  1487. $tbls = explode("\n", $r->tbl_names);
  1488. }
  1489. }
  1490. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
  1491. $configTbls = array();
  1492. Lib::loadClass('FoldersConfig');
  1493. if (!empty($tbls)) {
  1494. $folderConfAll = FoldersConfig::getRawData();
  1495. foreach ($tbls as $tblName) {
  1496. $tblName = trim($tblName);
  1497. if (empty($tblName)) continue;
  1498. $confTblName = "{$tblName}_COLUMN";
  1499. if (FoldersConfig::hasConfig($confTblName)) {
  1500. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1501. }
  1502. }
  1503. }
  1504. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1505. if (!empty($configTbls)) {
  1506. $this->_tbls = $configTbls;
  1507. }
  1508. return $this->_tbls;
  1509. }
  1510. public function installTable() {
  1511. if (!$this->_tbls) return;
  1512. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1513. $sql = "
  1514. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1515. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1516. `TBL_NAME` varchar(64),
  1517. `TBL_ID` int(11) NOT NULL,
  1518. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1519. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1520. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1521. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1522. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1523. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1524. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1525. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1526. PRIMARY KEY (`ID`),
  1527. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1528. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1529. ";
  1530. $this->_db->query($sql);
  1531. if ($this->_db->has_errors()) {
  1532. print_r($this->_db->get_errors());
  1533. }
  1534. }
  1535. public function generateTasksNewRecords() {
  1536. if (!$this->_tbls) return;
  1537. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1538. $sqlValues = array();
  1539. foreach ($this->_tbls as $tblName => $tblConf) {
  1540. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1541. }
  1542. $sqlValues = implode(',', $sqlValues);
  1543. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1544. values {$sqlValues};
  1545. ";
  1546. $res = $this->_db->query($sql);
  1547. if ($this->_db->has_errors()) {
  1548. print_r($this->_db->get_errors());
  1549. }
  1550. foreach ($this->_tbls as $tblName => $tblConf) {
  1551. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1552. select '{$tblName}' as TBL_NAME
  1553. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1554. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1555. from `{$tblName}` as t
  1556. where t.`A_STATUS`!='DELETED'
  1557. ";
  1558. $res = $this->_db->query($sql);
  1559. if ($this->_db->has_errors()) {
  1560. print_r($this->_db->get_errors());
  1561. }
  1562. }
  1563. }
  1564. public function generateTasksUpdated() {
  1565. if (!$this->_tbls) return;
  1566. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1567. foreach ($this->_tbls as $tblName => $tblConf) {
  1568. $sql = "update `{$this->_syncTblName}` as s
  1569. , `{$tblName}` as t
  1570. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1571. set
  1572. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1573. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1574. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1575. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1576. , s.`A_SYNCHRONIZED`=0
  1577. where
  1578. s.`TBL_ID`=t.`ID`
  1579. and s.`TBL_NAME`='{$tblName}'
  1580. -- and pt.`ID`=t.`P_ID`
  1581. and (
  1582. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1583. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1584. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1585. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1586. )
  1587. ";
  1588. $res = $this->_db->query($sql);
  1589. if ($this->_db->has_errors()) {
  1590. print_r($this->_db->get_errors());
  1591. }
  1592. }
  1593. }
  1594. public function newFilesAction() {
  1595. if (!$this->_tbls) return;
  1596. foreach ($this->_tbls as $tblName => $tblConf) {
  1597. $task = $this->_getTaskNewFiles($tblName);
  1598. $taskResult = $this->_fixLastModifiedFiles($task);
  1599. $this->_saveTask($tblName, -1);
  1600. }
  1601. }
  1602. private function _getTaskNewFiles($tblName) {
  1603. $task = null;
  1604. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1605. $sql = "select s.*
  1606. from `{$this->_syncTblName}` as s
  1607. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1608. ";
  1609. $res = $this->_db->query($sql);
  1610. if ($r = $this->_db->fetch($res)) {
  1611. $task = $r;
  1612. }
  1613. if (!$task) {
  1614. $task = new stdClass();
  1615. $task->TBL_NAME = $tblName;
  1616. $task->TBL_ID = -1;
  1617. $task->A_SYNC_RESULT = new stdClass();
  1618. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  1619. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  1620. }
  1621. return $task;
  1622. }
  1623. private function _fixLastModifiedFiles($task) {
  1624. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1625. $tblName = $task->TBL_NAME;
  1626. 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>';}
  1627. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1628. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1629. $record = null;
  1630. $folderConf = FoldersConfig::getAll($confTblName);
  1631. $uploader = new FileUploader($confTblName, $record);
  1632. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1633. trigger_error("Error: folders config!", E_USER_NOTICE);
  1634. die("Error: folders config!");
  1635. }
  1636. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1637. $foundTblFiles = array();
  1638. 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>';}
  1639. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1640. $filesWithPerms = array();
  1641. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1642. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1643. if (!empty($filesWithPerms)) {
  1644. $filesWithPermsTree = array();
  1645. $lastName = '';
  1646. foreach ($filesWithPerms as $line) {
  1647. if (substr($line, 0, 1) == '-') {// file name
  1648. $fileParts = array();
  1649. $filePartsArr = explode(' ', $line);
  1650. $lastInd = 0;
  1651. foreach ($filePartsArr as $vPart) {
  1652. if ($lastInd > 7) {// file name
  1653. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1654. $lastInd++;
  1655. }
  1656. else if (!empty($vPart) || $vPart === '0') {
  1657. $fileParts[] = $vPart;
  1658. $lastInd++;
  1659. }
  1660. }
  1661. $file = new stdClass();
  1662. if (!isset($fileParts[8])) {
  1663. 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>';
  1664. //continue;
  1665. }
  1666. $file->name = end($fileParts);
  1667. $file->path = end($fileParts);
  1668. //$file->owner = $fileParts[2];
  1669. //$file->group = $fileParts[3];
  1670. //$file->perms = $fileParts[0];
  1671. $file->isDir = (substr($line, 0, 1) == 'd');
  1672. $file->permsExt = array();
  1673. $filesWithPermsTree[$file->name] = $file;
  1674. $lastName = $file->name;
  1675. }
  1676. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1677. if ($lastName == '..') {
  1678. continue;
  1679. }
  1680. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1681. }
  1682. else {// parse error
  1683. $lastName = '..';
  1684. }
  1685. }
  1686. foreach ($filesWithPermsTree as $vFile) {
  1687. $vFile->path = ltrim($vFile->path, './');
  1688. $vFile->path = explode('/', $vFile->path);
  1689. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1690. $vFile->path = implode('/', $vFile->path);
  1691. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1692. $tblId = 0;
  1693. if ($hasRecordOwnFolder) {
  1694. $tblId = explode('.', $vFile->recordFolder);
  1695. $tblId = reset($tblId);
  1696. }
  1697. else {
  1698. $tblId = explode('.', $vFile->path);
  1699. $tblId = reset($tblId);
  1700. }
  1701. if (is_numeric($tblId) && $tblId > 0) {
  1702. $foundTblFiles[$tblId][] = $vFile;
  1703. }
  1704. }
  1705. }
  1706. 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>';}
  1707. 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>';}
  1708. if (!empty($foundTblFiles)) {
  1709. $rowsIds = array_keys($foundTblFiles);
  1710. $sql = "select t.`ID`
  1711. , t.`L_APPOITMENT_USER`
  1712. , t.`A_ADM_COMPANY`
  1713. , t.`A_CLASSIFIED`
  1714. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1715. from `{$task->TBL_NAME}` as t
  1716. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1717. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1718. ";
  1719. $res = $this->_db->query($sql);
  1720. while ($r = $this->_db->fetch($res)) {
  1721. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1722. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1723. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1724. if (!empty($cmdList)) {
  1725. 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>';}
  1726. foreach ($cmdList as $vCmd) {
  1727. 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>';}
  1728. exec($vCmd, $out, $outValue);
  1729. 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>';}
  1730. if ($outValue != 0) {
  1731. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1732. }
  1733. }
  1734. } else {
  1735. 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>';}
  1736. }
  1737. }
  1738. }
  1739. }
  1740. }
  1741. private function _getRequiredPermsExtByRecord($record) {
  1742. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1743. $requirePermsExt = array();
  1744. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1745. // TODO: group PODMIOT
  1746. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1747. }
  1748. else {
  1749. if ($record->L_APPOITMENT_USER) {
  1750. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1751. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1752. } else {
  1753. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1754. }
  1755. }
  1756. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1757. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1758. }
  1759. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1760. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1761. }
  1762. else {
  1763. if ($record->A_ADM_COMPANY) {
  1764. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1765. }
  1766. if ($record->A_CLASSIFIED) {
  1767. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1768. }
  1769. }
  1770. }
  1771. // add parent owner
  1772. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1773. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1774. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1775. } else {
  1776. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1777. }
  1778. }
  1779. // add user:_www perms read, write
  1780. $requirePermsExt["user:_www"] = array('write', 'read');
  1781. return $requirePermsExt;
  1782. }
  1783. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1784. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1785. $cmdList = array();
  1786. $vReqPermsExt = array();
  1787. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1788. $vReqPermsExt[$kPermObj] = array();
  1789. foreach ($vPerms as $vPerm) {
  1790. if ($vFile->isDir) {
  1791. if ($vPerm == 'read') {
  1792. $vReqPermsExt[$kPermObj]['list'] = 0;
  1793. $vReqPermsExt[$kPermObj]['search'] = 0;
  1794. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1795. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1796. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1797. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1798. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1799. }
  1800. else if ($vPerm == 'write') {
  1801. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1802. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1803. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1804. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1805. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1806. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1807. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1808. }
  1809. }
  1810. else {
  1811. if ($vPerm == 'read') {
  1812. $vReqPermsExt[$kPermObj]['read'] = 0;
  1813. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1814. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1815. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1816. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1817. }
  1818. else if ($vPerm == 'write') {
  1819. $vReqPermsExt[$kPermObj]['write'] = 0;
  1820. $vReqPermsExt[$kPermObj]['append'] = 0;
  1821. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1822. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1823. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1824. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. $permsToRemove = array();
  1830. foreach ($vFile->permsExt as $vPermExtLine) {
  1831. $vPermExtArr = explode(' ', $vPermExtLine);
  1832. $vPermExt = new stdClass();
  1833. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1834. $vPermExt->permObj = $vPermExtArr[1];
  1835. $vPermExt->perms = '';
  1836. if (count($vPermExtArr) == 4) {
  1837. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1838. }
  1839. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1840. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1841. }
  1842. else {
  1843. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1844. continue;
  1845. }
  1846. $permFound = false;
  1847. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1848. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1849. foreach ($vPerms as $kPerm => $vPermChecked) {
  1850. if (in_array($kPerm, $vPermExt->perms)) {
  1851. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1852. $permFound = true;
  1853. }
  1854. }
  1855. }
  1856. }
  1857. if (!$permFound) {
  1858. $permsToRemove[] = $vPermExt->nr;
  1859. }
  1860. //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>';
  1861. }
  1862. if (!empty($permsToRemove)) {
  1863. 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>';}
  1864. $permsToRemove = array_reverse($permsToRemove);
  1865. foreach ($permsToRemove as $vPermInd) {
  1866. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1867. }
  1868. }
  1869. $permsToAdd = array();
  1870. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1871. foreach ($vPerms as $kPerm => $vPermChecked) {
  1872. if (!$vPermChecked) {
  1873. $permsToAdd[$kPermObj][$kPerm] = 1;
  1874. }
  1875. }
  1876. }
  1877. if (!empty($permsToAdd)) {
  1878. 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>';}
  1879. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1880. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1881. }
  1882. }
  1883. return $cmdList;
  1884. }
  1885. private function _isActiveUser($usrLogin) {
  1886. $activeLoginList = $this->_fetchActiveLoginList();
  1887. return in_array($usrLogin, $activeLoginList);
  1888. }
  1889. public function _fetchActiveLoginList() {
  1890. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1891. if (!is_array($this->_activeLoginList)) {
  1892. $this->_activeLoginList = array();
  1893. $sql = "select u.`ADM_ACCOUNT`
  1894. from `ADMIN_USERS` as u
  1895. where u.`A_STATUS` = 'NORMAL'
  1896. ";
  1897. $res = $this->_db->query($sql);
  1898. while ($r = $this->_db->fetch($res)) {
  1899. $this->_activeLoginList[] = $r->ADM_ACCOUNT;
  1900. }
  1901. }
  1902. return $this->_activeLoginList;
  1903. }
  1904. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1905. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1906. $sqlResult = '';
  1907. if ($result) {
  1908. $resultJson = json_encode($result);
  1909. $resultJson = $this->_db->_($resultJson);
  1910. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  1911. }
  1912. $sql = "update `{$this->_syncTblName}` as s
  1913. set
  1914. s.`A_LAST_SYNC`=NOW()
  1915. , s.`A_SYNCHRONIZED`={$taskDone}
  1916. {$sqlResult}
  1917. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1918. ";
  1919. $res = $this->_db->query($sql);
  1920. }
  1921. public function executeTask($tblName, $tblId) {
  1922. if (!$this->_tbls) return;
  1923. $task = $this->_getTask($tblName, $tblId);
  1924. if (!$task) return;
  1925. $this->_executeTask($task);
  1926. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1927. return $task;
  1928. }
  1929. public function nextTaskAction($tblName) {
  1930. if (!$this->_tbls) return;
  1931. $task = $this->_getTask($tblName);
  1932. if (!$task) return;
  1933. $this->_executeTask($task);
  1934. /*
  1935. if (isset($task->A_SYNC_RESULT->total)
  1936. && isset($task->A_SYNC_RESULT->lastDone)
  1937. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  1938. ) {
  1939. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  1940. } else {
  1941. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1942. }
  1943. */
  1944. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1945. return $task;
  1946. }
  1947. private function _getTask($tblName, $tblId = null) {
  1948. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1949. $task = null;
  1950. $recordFieldList = $this->_getRecordFieldList($tblName);
  1951. $recordFieldList[] = 'L_APPOITMENT_USER';
  1952. $recordFieldList[] = 'A_ADM_COMPANY';
  1953. $recordFieldList[] = 'A_CLASSIFIED';
  1954. $sqlRecordFields = array();
  1955. foreach ($recordFieldList as $fldName) {
  1956. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  1957. }
  1958. $sqlRecordFields = implode(',', $sqlRecordFields);
  1959. $sqlTblId = "and s.`TBL_ID`!=-1";
  1960. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  1961. $sql = "select s.*
  1962. , {$sqlRecordFields}
  1963. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  1964. from `{$this->_syncTblName}` as s
  1965. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  1966. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  1967. where
  1968. s.`TBL_NAME`='{$tblName}'
  1969. {$sqlTblId}
  1970. and s.`A_SYNCHRONIZED`=0
  1971. and s.`A_POMIN_SYNC`=0
  1972. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  1973. limit 1
  1974. ";
  1975. $res = $this->_db->query($sql);
  1976. if ($r = $this->_db->fetch($res)) {
  1977. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  1978. $task = $r;
  1979. $task->record = new stdClass();
  1980. foreach ($recordFieldList as $fldName) {
  1981. $aliasFldName = "t__{$fldName}";
  1982. $task->record->{$fldName} = $task->{$aliasFldName};
  1983. unset($task->{$aliasFldName});
  1984. }
  1985. }
  1986. return $task;
  1987. }
  1988. private function _getRecordFieldList($tblName) {
  1989. if (empty($this->_tbls[$tblName])) return;
  1990. $conf = $this->_tbls[$tblName];
  1991. $fldNames = array();
  1992. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  1993. $fldName = trim($fldName);
  1994. if (!empty($fldName)) $fldNames[$fldName] = true;
  1995. for ($i = 1; $i < 5; $i++) {
  1996. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  1997. $fldName = trim($fldName);
  1998. if (!empty($fldName)) $fldNames[$fldName] = true;
  1999. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  2000. $fldName = trim($fldName);
  2001. if (!empty($fldName)) $fldNames[$fldName] = true;
  2002. }
  2003. if (!in_array('ID', $fldNames)) {
  2004. $fldNames['ID'] = true;
  2005. }
  2006. return array_keys($fldNames);
  2007. }
  2008. private function _executeTask($task) {
  2009. 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>';}
  2010. $DBG_TIME = false;
  2011. $dbgTime = new stdClass();
  2012. $dbgTime->startTime = microtime(true);
  2013. $dbgTime->lastTime = $dbgTime->startTime;
  2014. $confTblName = "{$task->TBL_NAME}_COLUMN";
  2015. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  2016. $record = $task->record;
  2017. $folderConf = FoldersConfig::getAll($confTblName);
  2018. $uploader = new FileUploader($confTblName, $record);
  2019. $errMsg = '';
  2020. if (!$uploader->setConfig($folderConf, $errMsg)) {
  2021. trigger_error("Error: folders config!", E_USER_NOTICE);
  2022. die("Error: folders config!");
  2023. }
  2024. if ($DBG_TIME) {
  2025. $dbgTime->curTime = microtime(true);
  2026. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2027. $dbgTime->lastTime = $dbgTime->curTime;
  2028. }
  2029. $uploader->findFolder();
  2030. $mainFolder = $uploader->getDestFolder();
  2031. if ($DBG_TIME) {
  2032. $dbgTime->curTime = microtime(true);
  2033. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2034. $dbgTime->lastTime = $dbgTime->curTime;
  2035. }
  2036. 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>';}
  2037. if (!$mainFolder) {
  2038. $mainFolder = $uploader->generateFolderName();
  2039. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2040. 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>';}
  2041. @mkdir($mainFolderPath, 0770, true);
  2042. @chmod($mainFolderPath, 0770);
  2043. if (!file_exists($mainFolderPath)) {
  2044. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2045. return false;
  2046. }
  2047. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2048. $file = new stdClass();
  2049. $file->name = '.';
  2050. $file->path = '.';
  2051. //$file->owner = '';
  2052. //$file->group = '';
  2053. //$file->perms = '';
  2054. $file->isDir = true;
  2055. $file->permsExt = array();
  2056. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2057. 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>';}
  2058. }
  2059. else {
  2060. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2061. }
  2062. if ($DBG_TIME) {
  2063. $dbgTime->curTime = microtime(true);
  2064. 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";
  2065. $dbgTime->lastTime = $dbgTime->curTime;
  2066. }
  2067. if (!empty($cmdList)) {
  2068. foreach ($cmdList as $vCmd) {
  2069. 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>';}
  2070. exec($vCmd, $out, $outValue);
  2071. 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>';}
  2072. if ($outValue != 0) {
  2073. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2074. }
  2075. }
  2076. }
  2077. if ($DBG_TIME) {
  2078. $dbgTime->curTime = microtime(true);
  2079. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2080. $dbgTime->lastTime = $dbgTime->curTime;
  2081. }
  2082. 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>';}
  2083. }
  2084. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2085. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2086. $DBG_TIME = false;
  2087. $dbgTime = new stdClass();
  2088. $dbgTime->startTime = microtime(true);
  2089. $dbgTime->lastTime = $dbgTime->startTime;
  2090. $filesWithPerms = array();
  2091. if ($uploader->hasRecordOwnFolder()) {
  2092. $cmd = " ls -Rlea . ";
  2093. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2094. exec($cmd, $filesWithPerms);
  2095. }
  2096. else {
  2097. $lookGlob = $uploader->getFileSearchRegex();
  2098. $cmd = " ls -Rlea {$lookGlob} ";
  2099. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2100. exec($cmd, $filesWithPerms);
  2101. }
  2102. //echo "\n-----------------------\n";
  2103. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2104. if ($DBG_TIME) {
  2105. $dbgTime->curTime = microtime(true);
  2106. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2107. $dbgTime->lastTime = $dbgTime->curTime;
  2108. }
  2109. $filesWithPermsTree = array();
  2110. $lastName = '';
  2111. $folderParent = '';
  2112. foreach ($filesWithPerms as $line) {
  2113. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2114. $fileParts = array();
  2115. $filePartsArr = explode(' ', $line);
  2116. $lastInd = 0;
  2117. foreach ($filePartsArr as $vPart) {
  2118. if ($lastInd > 7) {// file name
  2119. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2120. $lastInd++;
  2121. }
  2122. else if (!empty($vPart) || $vPart === '0') {
  2123. $fileParts[] = $vPart;
  2124. $lastInd++;
  2125. }
  2126. }
  2127. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2128. $lastName = '..';
  2129. continue;
  2130. }
  2131. $file = new stdClass();
  2132. if (!isset($fileParts[8])) {
  2133. 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>';
  2134. //continue;
  2135. }
  2136. $file->name = end($fileParts);
  2137. $file->path = array();
  2138. if ($folderParent) $file->path[] = $folderParent;
  2139. $file->path[] = end($fileParts);
  2140. $file->path = implode('/', $file->path);
  2141. //$file->owner = $fileParts[2];
  2142. //$file->group = $fileParts[3];
  2143. //$file->perms = $fileParts[0];
  2144. $file->isDir = (substr($line, 0, 1) == 'd');
  2145. $file->permsExt = array();
  2146. $filesWithPermsTree[$file->name] = $file;
  2147. $lastName = $file;
  2148. }
  2149. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2150. if ($lastName == '..') {
  2151. continue;
  2152. }
  2153. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2154. }
  2155. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2156. $folderParent = substr($line, 2, -1);
  2157. }
  2158. else if (substr($line, 0, 5) == 'total') {
  2159. continue;
  2160. }
  2161. else if (empty($line)) {
  2162. $folderParent = '';
  2163. continue;
  2164. }
  2165. }
  2166. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2167. if ($DBG_TIME) {
  2168. $dbgTime->curTime = microtime(true);
  2169. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2170. $dbgTime->lastTime = $dbgTime->curTime;
  2171. }
  2172. 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>';}
  2173. // check perms
  2174. /*
  2175. files:
  2176. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2177. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2178. R read, execute, readattr, readextattr, readsecurity
  2179. dir:
  2180. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2181. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2182. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2183. */
  2184. $cmdList = array();
  2185. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2186. if (false) {
  2187. // TODO: $kFileName == '_PISMA' - readonly
  2188. // TODO: $vFile->path => _PISMA/...
  2189. }
  2190. else {
  2191. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2192. if (!empty($cmdFile)) {
  2193. foreach ($cmdFile as $vCmd) {
  2194. $cmdList[] = $vCmd;
  2195. }
  2196. }
  2197. }
  2198. }
  2199. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2200. //echo "\n-----------------------\n";
  2201. if ($DBG_TIME) {
  2202. $dbgTime->curTime = microtime(true);
  2203. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2204. $dbgTime->lastTime = $dbgTime->curTime;
  2205. }
  2206. return $cmdList;
  2207. }
  2208. }
  2209. ?>