bash_sync_perms.php 95 KB

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