bash_sync_perms.php 95 KB

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